Nico
02/10/2021, 9:07 PMsealed class Download
data class App(val name: String, val developer: Developer) : Download()
data class Movie(val title: String, val director: Person) : Download()
val download: Download = // ...
// placeholder syntax
val result = when(download) {
is App(.name, .developer: Person(val devName = .name))
if (devName == "Alice") -> "Alice's app $name"
is Movie(.title, .director: Person(val dirName = .name))
if (dirName == "Alice") -> "Alice's movie $name"
is App, Movie -> "Not by Alice"
}
Note how
- Matching is purely nominal thanks to a 'access' operator (I chose .
but could be &
or nothing at all, really)
- Nested patterns are achieved using :
for a 'is-of-type' relation
- Destructured properties (like .name
) are made available in the RHS of the when
clause
- Properties can be desambiguated by explicitly declaring new variables for them
- Guards can be used to match for equality
- Proposed syntax is in the spirit of https://youtrack.jetbrains.com/issue/KT-21661 or https://youtrack.jetbrains.com/issue/KT-44729
If deconstruction in Java is implemented as described in https://github.com/openjdk/amber-docs/blob/master/eg-drafts/deconstruction-patterns-records-and-classes.md#translation, the deconstructed parameters could correspond to the names of those of the record that <deconstruct>()
returnsNico
02/10/2021, 9:09 PMedrd
02/18/2021, 2:19 AMval result = when (download) {
is App(val name, val developer: Person(val name as devName))
if (devName == "Alice") -> "Alice's app $name"
is Movie(val title, val director: Person(val name as dirName))
if (dirName == "Alice") -> "Alice's movie $name"
is App, Movie -> "Not by Alice"
}
With as
resembling import aliases.
It's longer but IMO more consistent.Nico
02/18/2021, 8:36 AMAnimesh Sahu
02/23/2021, 9:20 AMval result = when(val tmp = download) {
is App -> with (tmp) {
if (developer.name == "Alice") "Alice's app $name"
}
is Movie -> with(tmp) {
if (developer.name == "Alice") "Alice's movie $name"
}
is App, Movie -> "Not by Alice"
}
I doubt we need a new syntax for this 🤔Nico
03/06/2021, 7:52 AMdeveloper
and director
are of class Person
To do that you would need nested whens, and that is what pattern matching is supposed to help with.
Additionally, your example uses normal if else as expressions, so I believe it doesn't compile: you need to provide an 'else' there. That's where guards come in: they allow avoid a branch and move on the next one.Nico
03/06/2021, 7:53 AMAnimesh Sahu
03/06/2021, 9:52 AM