2017-06-13 60 views
3

我是的新手,當我開始Null Safety時,我感到困惑。Kotlin NullPointerException發生

在初始化方面存在一些數據不一致性(未初始化,這在構造函數中可用)。

任何人都可以更詳細地描述情況嗎?適於從一個Kotlin discussion on exactly this

+3

5秒揭示此:https://discuss.kotlinlang.org/t/nre-from-an-uninitialized-this-in-constructor/1966 –

+1

@OliverCharlesworth首先感謝,我來自中國,對不起,我無法打開您的鏈接。先生,你可以在答案中寫下來嗎? –

回答

4

實施例:谷歌搜索

class Foo { 
    val c: String   // Non-nullable 

    init { 
     bar() 
     c = ""    // Initialised for the first time here 
    } 

    fun bar() { 
     println(c.length) // Oh dear 
    } 
} 

fun main(args: Array<String>) { 
    Foo() 
} 
+0

非常感謝,先生。我通過你的例子立即瞭解它。 –

相關問題