reitzig
February 27, 2018, 8:58am
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?
2 Likes
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
Also for more context, there is a really long discussion about this here: When desperately needs `it`
1 Like
I regularly find myself in the very same position as the OP.
reitzig
February 27, 2018, 6:40pm
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:
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
reitzig
February 27, 2018, 9:08pm
9
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 -> 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
1 Like
This was where I was referring to