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
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"
}
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With