scala - 返回一个扩展特征的案例类
问题描述
我需要定义返回一个扩展特征的案例类:
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)
知道如何实现吗?
解决方案
一旦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。
推荐阅读
- openstack - 使用梯形校正时遇到此错误
- twitter - 一些推特帖子有多个推文 ID
- css - keydown 触发 css 背景颜色变化
- bash - Flux 调试有什么用?在下面的代码中它检查什么。?
- ruby-on-rails - 从数据库中打印另一个类的所有对象和属性,ROR
- google-sheets - 如何在 Google 电子表格中使用自定义脚本进行条件格式设置?
- c++ - 澄清关系运算符重载的概念(需要调试帮助)
- vaadin - 在 Vaadin 8 和 10 的 Grid 视口中获取可见的项目
- android - 如何为我的一个项目恢复丢失的“src”文件夹
- video - 将原始 264 文件转换为 mp4 没有声音