直接引用内部案例类中的值或方法

时间:2018-12-16 23:24:18

标签: scala composition case-class

我想使组合案例类的API更加简洁。因此,请考虑经典示例的修改版本:

case class Address(street: String, city: String, zip: String) {
    some large collection of methods
}
case class Person(name: String, address: Address) {
    val street = address.street
    val city = address.city
    val zip = address.zip
}

现在,我喜欢这样,因为您可以直接从像person.city这样的人那里获取地址信息,而不需要person.address.city

但是,如果我们假设Address案例类上有大量的值或方法,而对于Person类中的val x = address.x则很繁琐。有什么方法可以直接从人那里访问地址中的字段,值和方法,而无需手工映射它们?

1 个答案:

答案 0 :(得分:2)

一个选项是使用隐式转换。但我不能证明这种方法有多干净:

case class Address(street: String)
case class Person(name: String, address: Address) {
  private val s = this.street
}
implicit def person2address(p: Person): Address = p.address

Person("alex", Address("street")).street

也可以使用self types

case class Person(name: String, address: Address) {
  _: Address =>
  private val s = street
}