Smartcast to from nullable to NotNull in run


#1

I was wondering, why cant I do this:

var nullable: Int? = 0

run {
	if(nullable == null || nullable < 5){
		nullable = 5
	}
}

The if statement works fine when I pull it out of the let block.
I mean I get, that you can’t do this if nullable was declared in a class, as that would lead to problems with multiple threads, but as far as I can tell, the compiler should be intelligent enough to figure out, that this is not the case. Kotlin wants you to use run for local blocks, but if you do so you can no longer smartcast nullables?

PS: obviously I have a more complex use case, but it boils down to this problem. It also does not work for let/run/also/apply which is where I would like to use it.


#2

Currently the compiler doesn’t know that run executes its functional parameter immediately and exactly once, therefore nullable becomes a captured var, and the compiler can no longer make assumptions about its state being unchanged after the null check.

This is a missing feature and we hope to improve this situation later.