Kotlin Error: Null can not be a value of a non-null type String

//这样延迟赋值,一定必须非空,否则崩溃
lateinit var view: V


fun attachView(view:V){
    this.view = view
}


fun detachView(){
    //这里会提示不能置空
    //Null can not be a value of a non-null type String
    this.view = null
}

lateinit var的值默认是非空的,如果有空,运行到那里马上崩给你看!!!

//所以需要改成以下初始化,
//初始化就给了一个空值,可空 类型后加一个?表示这个变量可空
var view: V? = null

fun attachView(view:V){
    this.view = view
}

fun detachView(){
    //这样下边这行就可以正常赋空值了
    this.view = null
}

猜你喜欢

转载自blog.csdn.net/Goals1989/article/details/128239213