Search code examples
nullkotlinkotlin-null-safety

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


Solution

  • 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"
            }
        }
    }