我想使组合案例类的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
则很繁琐。有什么方法可以直接从人那里访问地址中的字段,值和方法,而无需手工映射它们?
答案 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
}