Add implicit `this` to `when` statement


#1

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?


#2

Have you seen this topic?


#3

No, I must have overlooked that. IMHO it should be a fallback inside a when(x), in absence of name clashes even writing it.something should not be necessary, something alone should suffice.


#4

We’re tracking the request to make when with argument more powerful in KT-28359 and related issues.