Reputation: 3828
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
Upvotes: 4
Views: 184
Reputation: 692121
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"
}
}
}
Upvotes: 5
Reputation: 58507
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.
Upvotes: 3