Kotlin对类属性的null安全性

Mic*_*zuk 4 null kotlin kotlin-null-safety

如何避免使用!!类的可选属性

class PostDetailsActivity {

    private var post: Post? = null

    fun test() {
        if (post != null) {
            postDetailsTitle.text = post.title    // Error I have to still force using post!!.title
            postDetailsTitle.author = post.author

            Glide.with(this).load(post.featuredImage).into(postDetailsImage)

        } else {
            postDetailsTitle.text = "No title"
            postDetailsTitle.author = "Unknown author"

            Toast.makeText(this, resources.getText(R.string.post_error), Toast.LENGTH_LONG).show()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我应该创建一个局部变量吗?我认为使用!!不是一个好习惯

JB *_*zet 5

您可以使用申请:

fun test() {
    post.apply {
        if (this != null) {
            postDetailsTitle.text = title
        } else {
            postDetailsTitle.text = "No title"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

或者:

fun test() {
    with(post) {
        if (this != null) {
            postDetailsTitle.text = title
        } else {
            postDetailsTitle.text = "No title"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)