This is a generalization of #3442, but using kotlin.reflect APIs instead of optics (and only the part in the standard library, so we actually do not depend on the kotlin.reflect library). The result doesn't look so nice, but it can still be very useful.
val User.shownName: String get() = this.matchOrThrow {
Person::class.of(Person::name.of(Name::firstName), Person::age.suchThat { it < 18 }) then { (fn, _) -> fn }
Person::class.of(Person::name.of(Name::firstName, Name::lastName)) then { (fn, ln) -> "Sir/Madam $fn $ln" }
Company::class.of(Company::name, Company::director.of(Name::lastName)) then { (nm, d) -> "$nm, att. $d" }
}
Implementation note: I started with even shorter code, without .of (Person::name(Name::firstName)). However, it turns out that this is reserved syntax, so I had to come up with a small name instead.
This is a generalization of #3442, but using
kotlin.reflect
APIs instead of optics (and only the part in the standard library, so we actually do not depend on thekotlin.reflect
library). The result doesn't look so nice, but it can still be very useful.Implementation note: I started with even shorter code, without
.of
(Person::name(Name::firstName)
). However, it turns out that this is reserved syntax, so I had to come up with a small name instead.