Scope when expression with it

It would be nice to scope when expression with it in order to simplify this use case

when (val response = executeRequest()) {
	is Success -> response.body
	is HttpError -> throw HttpException(response.status)
}

in this way

when (executeRequest()) {
	is Success -> it.body
	is HttpError -> throw HttpException(response.status)
}

That would be a breaking change as it would change the behavior of the following:

"foo".let {
    when("bar") {
        is String -> println(it)
    }
}

That shouldn’t be a problem, as long as it can be renamed as usual

"foo".let { a ->
    when("bar") { b ->
        is String -> println(b)
    }
}

“breaking change” means that it changes the behaviour of existing code.
The fix is easy, but someone would need to do it.

In general if a change in the languare requires fixing existing code, it won’t be made.

This topic was already discussed here:
When desperately needs `it` - #25 by gladed2 and declaring a val inside the when clause was basically the outcome.

1 Like