I'd like to make the API of a composed case class a little cleaner. So, consider a modified version of the classic example:
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
}
Now, I like this because you can get the address info directly from the person like person.city
instead of requiring person.address.city
However if we imagine that there are a large number of values or methods on the Address
case class and it would be tedious to val x = address.x
in the Person class. Is there some way to directly access field, values, and methods in address from a person without mapping them all by hand?
one option is to use an implicit conversion. but i would not justify how clean this approach is:
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
also self types could be used:
case class Person(name: String, address: Address) {
_: Address =>
private val s = street
}