Kotlin null-safety for class properties

How can I avoid using !!for additional class properties

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

Create a local variable? I think use is !!not good practice.

+4
source share
2 answers

You can use apply:

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

or using:

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

It:

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

It can be replaced by:

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

If the expression to the left of ?: is not null, the elvis operator returns it, otherwise it returns the expression to the right.

+3
source

Source: https://habr.com/ru/post/1674285/


All Articles