简体   繁体   English

斯卡拉。 来自特征参考的案例类副本

[英]Scala. Case class copy from trait reference

Hi I'm trying to solve a problem in kind of "elegant" and type safe way but I can't find the best...嗨,我正在尝试以“优雅”和安全的方式解决问题,但我找不到最好的...

Let's say I have this trait假设我有这个特质

trait Event {
  def deviceId: String
  def userId: String
  def eventDateTime: DateTime
  def payload: Option[Payload]
}

trait Payload

And following case classes (there could be more)以及以下案例类(可能还有更多)

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)

I would like to use case class copy method directly from the trait without casting to AEvent or BEvent...我想直接从特征使用案例类复制方法,而不需要转换为 AEvent 或 BEvent ...

As I'm having a reference to the trait, best solution I figured out is to create a method like this:由于我引用了该特征,因此我想出的最佳解决方案是创建一个这样的方法:

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]
}

What I don't like is that Payload type is casted in runtime... How can I have type check during compile time?我不喜欢的是 Payload 类型是在运行时强制转换的...如何在编译时进行类型检查?

Thanks in advance提前致谢

What about关于什么

case class Event[P <: Payload](deviceId: String, userId: String, eventDateTime: DateTime, payload: Option[P])

and using Event[APayload] instead of AEvent ?并使用Event[APayload]而不是AEvent

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM