嗨,我正在尝试以"优雅"和类型安全的方式解决问题,但我找不到最好的......
假设我有这个特质
trait Event {
def deviceId: String
def userId: String
def eventDateTime: DateTime
def payload: Option[Payload]
}
trait Payload
以下案例类(可能还有更多)
case class AEvent (deviceId: String, userId: String, eventDateTime: DateTime, payload: Option[APayload]) extends Event
case class APayload (content: String)
case class BEvent (deviceId: String, userId: String, eventDateTime: DateTime, payload: Option[BPayload]) extends Event
case class BPayload (size: Int, name: String)
我想直接从特征中使用案例类复制方法,而无需转换为 AEvent 或 BEvent...
由于我引用了该特征,我想出的最佳解决方案是创建这样的方法:
def copy[T <: Event](event: T)(deviceId: String = event.deviceId,
userId: String = event.userId,
eventDateTime: DateTime = event.eventDateTime,
payload: Option[Payload] = event.payload) T = {
val res = event match {
case x: AEvent => AEvent(deviceId, userId, eventDateTime, payload.asInstanceOf[APayload])
case x: BEvent => BEvent(deviceId, userId, eventDateTime, payload.asInstanceOf[BPayload])
}
res.asInstanceOf[T]
}
我不喜欢的是有效负载类型是在运行时强制转换的......如何在编译时进行类型检查?
提前致谢
怎么样
case class Event[P <: Payload](deviceId: String, userId: String, eventDateTime: DateTime, payload: Option[P])
并使用Event[APayload]
而不是AEvent
?