2017-04-07 86 views
4

我怎样才能避免使用!!类的可选属性科特林空安全的类属性

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() 
     } 
    } 
} 

我应该创建一个局部变量?我想用!!是不是一个好的做法

+3

Android的工作室为您提供了理由_“‘后’是可能已经被改变了可变特性这次”_。根据你打算如何使用'title',一种可能的选择是'post?.apply {title}' – Michael

+0

如果我需要像'else'这样的替代条件,该怎么办? –

+0

您能否发表您想要达到的完整示例? –

回答

5

您可以使用适用于:

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

这似乎是单一财产最直接的解决方案。 'let'也可以使用。另请参阅[这里](https://discuss.kotlinlang.org/t/kotlin-null-check-for-multiple-nullable-vars/1946/13?u=mfulton26)多个属性。 – mfulton26

3

此:

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" 

如果表达式的左侧:不为空,则elvis运算符返回它,否则返回右边的表达式。

+0

我简化了一点点所有的代码我有一些其他的属性 –

+0

那么,它仍然是每个属性的一行。 'postDetailsTitle.propertyX =交.propertyX:??defaultX' – Michael

+0

我不想复制完整的类,我添加了几行 –