‘Subject variable in when’ is one of the features considered in the recent future features poll. If it were to be implemented, the most likely syntax is:
when (val f = foo()) {
is Bar -> println(f.barProp)
is Baz -> println(f.bazProp)
}
The problem with using 'it' to refer to the subject variable is that it might lead to confusion if there was a lambda expression within the when statement.
Yes, it’s a pity that 'it' can’t be used because of the lambda problem.
I suppose you could use a different word such as 'that' or 'expr' but even this wouldn’t be perfect as there could still be problems if one 'when' was nested inside another.
So I think the best solution is to allow the programmer to choose an appropriate name for the subject variable.
Your own suggestion looks similar to the pattern-matching 'switch' statement in C# 7.0 where each 'case', if it represents a type, can be given its own variable. It’s another possibility for them to mull over but it’s a bit complicated for my taste - I’d prefer a single variable to be used for the whole 'when' which is what’s done in Go.
Scala uses a similar format in its partial functions (case x if ... => ... ) . I was actually disappointed Kotlin didn’t have a Partial Function type because then you could easily have foo().when { is Bar -> println(it) }, and when wouldn’t even need to be a keyword, just an extension function.
You’re right that repeating the bound variable name is a little verbose, but there are times when you don’t need anything bound in every case. And TBH too many when cases seems like a smell that ought to look a little ugly anyway.
As for val…I’m actually not a fan of sticking val in there. It suggests val x = 0 is an expression when it’s not.
If you don’t want the feature that’s fine, don’t vote for it. But I’ve used bound variables on pattern matches in Scala and it always made for more concise, readable code.
Point 2 is a perfect example showing why Kotlin is better, and what I mean by “less fluff”. Type inference, smoother syntax, and so forth makes the code is easier to read, write, and debug. It’s a huge advantage over Java.
Suggestion 3 does not help. Indentation is shorthand for “here is a new multiline scope”. By collapsing the visual marker the code is more dense and harder to read. Any Kotklin reformatter will put the newlines right back where they should be.
If we can deal with nested lambdas, I’m sure we can deal with adding when to the mix. It almost looks like a lambda, anyway. (And it might be a function if we had hash literals.)