Give when implicit access to the value under consideration


#1

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

when (foo.computeBar().something) {
	is CaseA -> it.name
	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?


Suggest new operation combining 'when' & 'with'
#2

You could do something like:

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

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


#3

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


#4

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


#5

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

Relevant entry from there:


#6

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


#7

Can you explain how?


#8

#9

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


#10

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 -> it.name
	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


#11

This was where I was referring to