首页 > 解决方案 > 返回一个扩展特征的案例类

问题描述

我需要定义返回一个扩展特征的案例类:

trait Id {
  def id: Long
}

case class Person(name: String)

val john = Person("John") 
val johnWithId: Person with Id = /*person -> 123L*/ ???

知道如何实现吗?

我试图减少代码的重复,这就是为什么我没有像这样声明一个 trait Person:

trait Id {
  def id: Long
}

trait Person {
  def name: String
}

case class PersonWithoutId(name: String) extends Person

case class PersonWithId(name: String, id: Long) extends Person with Id

val john = PersonWithoutId("John")
val johnWithId: Person with Id = PersonWithId(person.name, 123L)

知道如何实现吗?

标签: scalatraitscase-class

解决方案


一旦Person已经实例化,就为时已晚 - 在实例已经实例化后,您无法更改john实例。但是,您可以实例化 a Person with Id

val johnWithId: Person with Id = new Person("John") with Id {
  override def id: Long = 123L
}

请注意,这并不等同于使用PersonWithId(name: String, id: Long)案例类,例如 -equals并且hashcode忽略此实现中的 ID。


推荐阅读