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
Post a Comment