class 属性的 Kotlin 空安全
Kotlin null-safety for class properties
如何避免将 !!
用于 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()
}
}
}
我应该创建一个局部变量吗?我认为使用 !!
不是一个好习惯
这个:
if (post != null) {
postDetailsTitle.text = post.title // Error I have to still force using post!!.title
} else {
postDetailsTitle.text = "No title"
}
可以替换为:
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.
您可以使用申请:
fun test() {
post.apply {
if (this != null) {
postDetailsTitle.text = title
} else {
postDetailsTitle.text = "No title"
}
}
}
或与:
fun test() {
with(post) {
if (this != null) {
postDetailsTitle.text = title
} else {
postDetailsTitle.text = "No title"
}
}
}
如何避免将 !!
用于 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()
}
}
}
我应该创建一个局部变量吗?我认为使用 !!
不是一个好习惯
这个:
if (post != null) {
postDetailsTitle.text = post.title // Error I have to still force using post!!.title
} else {
postDetailsTitle.text = "No title"
}
可以替换为:
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.
您可以使用申请:
fun test() {
post.apply {
if (this != null) {
postDetailsTitle.text = title
} else {
postDetailsTitle.text = "No title"
}
}
}
或与:
fun test() {
with(post) {
if (this != null) {
postDetailsTitle.text = title
} else {
postDetailsTitle.text = "No title"
}
}
}