Why doesn't Kotlin allow to use lateinit with primitive types?

前端 未结 3 1201
-上瘾入骨i
-上瘾入骨i 2020-11-29 05:32

In the Kotlin language we, by default, have to initialize each variable when it is introduced. To avoid this, the lateinit keyword can be used. Referring to a <

3条回答
  •  醉梦人生
    2020-11-29 06:23

    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) {
        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
    }
    

提交回复
热议问题