您好,我试图通过优雅的方式来解决问题"并输入安全的方式,但我找不到最好的......
让我说我有这个特质
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)
我想直接从特征中使用case类复制方法而不会转换为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]
}
我不喜欢的是Payload类型是在运行时输入的...... 如何在编译期间进行类型检查?
提前致谢
答案 0 :(得分:0)
怎么样?
case class Event[P <: Payload](deviceId: String, userId: String, eventDateTime: DateTime, payload: Option[P])
并使用Event[APayload]
代替AEvent
?