A short answer is that with primitives you can always use 0
as the default, and with nullable types null
as a default. Only non-nullable non-primitive types may need lateinit
to work around the type safety system.
Actually, there is no need for initializing a variable in Kotlin as long as it has a value before the first access and it can be statically proved. Which means this code is perfectly valid:
fun main(args: Array<String>) {
var x: Int
val y: Double
x = 0
y = x + 0.1
println("$x, $y")
}
But there are (rare) cases when the initialisation cannot be statically proved. The most common case is a class field which uses any form of dependency injection:
class Window {
@Inject lateinit parent: Parent
}
lateinit var foo: Int
, the error message says'lateinit' modifier is not allowed on properties of primitive types
, implying thatInt
is a primitive type, even though Kotlin is supposed to be able to use either int or Integer under the hood as needed. I think this inconsistency (or ambiguity, at best) adds a lot to the confusion. – Biomeint
variable lateinit, because it's a primitive type in the strict sense; but this doesn't tell us why you can't make anInt
variable lateinit (sinceInt
is not always implemented as a primitive type under the hood). – Biome