Kotlin null-safety for class properties -


how can avoid using !! optional properties of class

class postdetailsactivity {      private var post: post? = null      fun test() {         if (post != null) {             postdetailstitle.text = post.title    // error have 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 create local variable? think using !! not practice

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

Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -