arrow-kt / arrow

Λrrow - Functional companion to Kotlin's Standard Library
http://arrow-kt.io
Other
6.13k stars 442 forks source link

Pattern matching with `KClass` and `KProperty` #3449

Open serras opened 3 months ago

serras commented 3 months ago

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.

github-actions[bot] commented 3 months ago

Kover Report

Total Project Coverage 60.69%
nomisRev commented 2 months ago

Sorry for the hold-up @serras. This is on my backlog for asap.