Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin null-safety for class properties

How can I avoid using !! for optional properties of class

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

Should I create a local variable? I think using !! is not a good practice

like image 682
Michał Jurczuk Avatar asked Feb 04 '23 17:02

Michał Jurczuk


2 Answers

You can use apply:

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

or with:

fun test() {
    with(post) {
        if (this != null) {
            postDetailsTitle.text = title
        } else {
            postDetailsTitle.text = "No title"
        }
    }
}
like image 157
JB Nizet Avatar answered Feb 08 '23 15:02

JB Nizet


This:

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

Could be replaced with:

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.

like image 32
Michael Avatar answered Feb 08 '23 15:02

Michael