When desperately needs `it`


Although I don’t think that using ‘it’ would be out of the question, you’d need to be aware of possible clashes with the use of ‘it’ not just in single parameter nested lambdas but also in such a lambda enclosing the ‘when’ statement.

Because of this, I’d be very surprised if they opted for that ( if indeed they decide to do anything at all) when the alternative of using a user-defined variable does not have these problems.


It’s not just “saving a line”; in highly-nested code using when’s return value, having to pre-assign the variable can split up code in ways that disrupt code readability and flow.

As a rather simple example of what I’m talking about:

    val content = someOtherCall()
        when(content) {
            is ObjectContent -> content.value
            is StringContent -> content.str
            else -> ""

But the “it” version is an awkward ask that has too many style and substance things going against it. The syntax should be more similar to a for loop whether it be when(val foo = stuff()) or whatever.


You can do:

call(command, someOtherCall().run { when(this) {
    is ObjectContent -> value
    is StringContent -> str
    else -> ""

But it would be nice to collapse .run { when(this) { to just .when {:

call(command, someOtherCall().when {
    is ObjectContent -> value
    is StringContent -> str
    else -> ""


I believe that’d be run instead of apply (if I understand correctly, apply would return someOtherCall’s result instead of the lambda’s result).

Personally I’ve avoided "apply"s and "run"s and "with"s and such when I could precisely because what they do is so ambiguous from their names and they’re a bit like duck tape in that they patch things well, but not pretty. But I suppose that is a concise solution if one was needed.


You are right, I fixed the post. (IRL it wouldn’t have compiled.)

I’m trying to learn and use run/with/apply/etc because they are standard Kotlin. I agree with you that they feel clumsy at first but I am hoping time and practice will fix that. And of course in the IDE the definition is only one click away!


When I started using Kotlin I kinda felt the same. But now after a while I am used to them they are really nice. Once you know which of them return the original (also, apply) value and which the lambda (run, let) they make understanding the control flow of the program much easier as you can get away with far less temporary values.


A related KEEP has been proposed: Local variable declaration in ‘when’ subject

Implemented in 1.3-M1. Yay!