Kotlin 三元运算符

Kotlin ternary operator

如何将以下代码从 Java 转换为 Kotlin?

Boolean mBoolean = false
view.setVisibility(mBoolean ? View.VISIBLE : View.GONE);
val mBoolean = false
view.visibility = if(mBoolean) View.VISIBLE else View.GONE

但是我怀疑在这里使 mBoolean 不可变是否有意义,所以我会使用 var mBoolean.

而不是 val mBoolean

您可以通过创建扩展函数

扩展 view.visibility = if(mBoolean) View.VISIBLE else View.GONE
fun View.makeVisible(show:Boolean){
    this.visibilility = if(show) View.VISIBLE else View.GONE   
}


var mBolean = false
view.makeVisible(mBoolean)

您还可以使用 when 运算符:

 val mBoolean = false
        view.visibility = when (mBoolean) {
            true -> View.VISIBLE
            false -> View.GONE
        }