swift initializes nullable variables automatically...
# language-proposals
e
swift initializes nullable variables automatically to
null
, could kotlin do the same?
🚫 4
😱 1
k
It's nice to have an error when you forget to initialize something in the else branch, this comes up with
if
a lot:
Copy code
val x: Int?
if (bool) {
    x = 5
}
print(x) //error
4
Automatic initialization would remove that error completely.
l
Don't be too lazy, risking lack of explicitness
👍 1
e
given it's nullable, you think about it, being null is actually legit
@louiscad laziness is a risky objection, people could say the same over other things we already have, such as type inference
l
Karel showed how useful it is to make a difference with deferred initialization and null initialized. The compiler uses that to check correctness of the code.
e
actually that is an invalid example. If you declare it as nullable, it means
null
is a valid state
if you want to catch those errors, declare it as non-nullable
k
I know, it's intentional.
null
is a valid state but I want to explicitly set the variable in each branch to make sure I don't mess up.
e
then I think it's a very rare situation
k
Really? What is your use case where you don't want te be this explicit?
e
I mean, you want a nullable and you want anyway the compiler to throw an error whenever you forget to set a value other than null. It looks pretty niche to me
1
if you think about, declaring non-nullable type serves exactly that purpouse
k
I did a grep in my current code, turns out I have no instances of either case (null-initialize a variable to later overwrite it or non-initialize it and then set it in both branches). Still, I like the consistent rule that you need to initialize everything.
l
This is helpful at writing time.
e
@karelpeeters then use non nullable together with
lateinit
k
But then it isn't a
val
anymore.
lateinit
is just a typesystem hack, not really a solution.