Give when implicit access to the value under consideration


I find myself regulary wishing I could write something like this:

when (foo.computeBar().something) {
	is CaseA ->
	is CaseB -> it.description
	else -> it.toString()

Of course, it’s not possible and I have to create explicit local variables (that survive the scope of when!) for each value I want to switch over.

As far as I can tell, this would be an additive and rather natural change. What do you think?


You could do something like:

foo.computeBar().something.let {
    when (it) {
        is CaseA ->
        is CaseB -> it.description
        else -> it.toString()

Which I think is easy to understand doesn’t add much code


Also for more context, there is a really long discussion about this here: When desperately needs `it`


I regularly find myself in the very same position as the OP.


Thanks for the pointer. I was confused that my search turned up empty, seemed a very natural request to me.

Relevant entry from there:


It is not possible because it would break backwards compatibility

Can’t find the topic right now, but there was a discussion on being able to provide the when_syntaxis for a own label, so it’s easier to create a dsl.
Looks like this can be integrated with that suggestion


Can you explain how?



True, thanks. Doesn’t mean it can’t be considered for Kotlin 2.0+, though.


I have in another thread suggested that there be a form of when that can be applied to an expression using dot as in:

foo.computeBar().something).when {
	is CaseA ->
	is CaseB -> it.description
	else -> it.toString()

The .when{…} would be equivalent to .let { when(it) {…} }

This would not be a breaking change since that is not valid syntax. It does however require a language change, not just a library addition


This was where I was referring to