Reputation: 337
I have a code like this (inside a function):
var a: String?
if (a != null) {
// doSometing()
}
I debugged a code without the if statement and saw that a null value is assigned to a variable by default. So why compiler cause an error saying:
Variable 'a' must be initialized
What am I missing here?
Upvotes: 1
Views: 862
Reputation: 29844
Of course you can just compile and run something like this:
var a: String?
println() // breakpoint here
The debugger will show a
as initialized with null
. If you look at the decompiled byte code you will see the same:
public static final void main() {
String a = null;
// ...
}
It is a restriction of the language itself to initialize every variable. Let's take a look at the Kotlin language specification (12.2.2) for that:
Kotlin allows non-delegated properties to not have initializers in their declaration as long as the property is definitely assigned before its first usage.
It seems that the language specification refers to even local variables as properties. See here.
Since, we don't use it in my example that would be ok, still it does have to have some value internally, right?
Now you will wonder, how Kotlin keeps track of uninitialized variables then, when they already have been assigned null
:
This property is checked by the variable initialization analysis (VIA). VIA operates on abstract values from a flat assignedness lattice of two values {Assigned, Unassigned}. [...]
In simple terms you can image it like the compiler keeps track of each variable in a list with either the state "Assigned" or "Unassigned".
Upvotes: 2