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

Merged
merged 6 commits into from
Oct 2, 2024
Merged

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

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

@nomisRev
Copy link
Member

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

Copy link
Member

@nomisRev nomisRev left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Couple of small nits, and questions.

Also, does arrow-match belong to arrow-optics if it doesn't depend on optics? Maybe we can consider putting it completely separate, or under core as well. Wherever you think this fits best.

@serras
Copy link
Member Author

serras commented Oct 2, 2024

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 serras merged commit 6ff4400 into main Oct 2, 2024
11 checks passed
@serras serras deleted the serras/core-pattern-match branch October 2, 2024 17:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants