【发布时间】:2018-04-11 16:10:57
【问题描述】:
您好,我正在尝试以一种“优雅”和安全的方式解决问题,但我找不到最好的...
假设我有这个特质
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]
}
我不喜欢的是 Payload 类型是在运行时强制转换的...... 如何在编译时进行类型检查?
提前致谢
【问题讨论】:
标签: scala types case-class