Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pattern matching with KClass and KProperty #3449

Open
wants to merge 4 commits into
base: main
Choose a base branch
from

Conversation

serras
Copy link
Member

@serras serras commented Jun 4, 2024

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.

Copy link
Contributor

github-actions bot commented Jun 4, 2024

Kover Report

Total Project Coverage 60.69%

@nomisRev
Copy link
Member

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants