arrow icon indicating copy to clipboard operation
arrow copied to clipboard

Pattern matching with `KClass` and `KProperty`

Open serras opened this issue 1 year ago • 2 comments

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.

serras avatar Jun 04 '24 12:06 serras

Kover Report

File Coverage [32.50%]
arrow-libs/optics/arrow-optics/src/commonMain/kotlin/arrow/optics/match/Combinators.kt 32.50%
Total Project Coverage 60.34%

github-actions[bot] avatar Jun 04 '24 12:06 github-actions[bot]

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

nomisRev avatar Jun 19 '24 06:06 nomisRev

Also, does arrow-match belong to arrow-optics if it doesn't depend on optics?

I'm not really sure about where it should be. In my mind it goes in optics because it's about immutable data inspection, like optics.

Also, I fear we end up with a super-big core folder.

serras avatar Oct 02 '24 16:10 serras