Consider the following Kotlin snippet:
val person = // ...
when {
person == null -> "Absent!"
person.age < 18 -> "Too young!"
person.age > 60 -> "Too old!"
else -> "Ok!"
// note that we have to repeat "person." several times
}
That’s okay, but we already have the when(x)
syntax. Alas, even though all cases above operate on a single variable (person
), we cannot do the age checks in a when(x)
statement.
Back in the days when I was coding in Delphi (I’m getting old…) there was a with(x){ }
statement, and within the braces, there would be an implicit this
which is set to the x
set in the brackets. This could also be used in the when(x)
statement.
For example, with this we could rewrite the when
statement above to:
val person = // ...
when(person){
null -> "Absent!" // this already works fine in kotlin
age < 18 -> "Too young!" // "age" means person.age
age > 60 -> "Too old!" // here as well
else -> "Ok!"
}
In case of variable name clashes, we could also prefix the property with it
:
val person = // ...
val age = someUnrelatedAgeNumberToSimulateClashing
when(person){
null -> "Absent!" // this already works fine in kotlin
it.age < 18 -> "Too young!" // note that we use 'it' here because age is ambiguous
it.age > 60 -> "Too old!" // here as well
else -> "Ok!"
}
This would make the when(x)
statement a lot more powerful, allow for better readability and more concise code.
Any thoughts / comments?