Kotlin对类属性的null安全性

时间:2017-04-07 08:13:04

标签: 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()
        }
    }
}

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

2 个答案:

答案 0 :(得分:5)

您可以使用apply:

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

或与:

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

答案 1 :(得分:3)

此:

if (post != null) {
    postDetailsTitle.text = post.title    // Error I have to still force using post!!.title
} else {
    postDetailsTitle.text = "No title"
}

可以替换为:

postDetailsTitle.text = post?.title ?: "No title"
  

如果?:左边的表达式不为null,则elvis运算符返回它,否则返回右边的表达式。