Kotlin三元运算符

时间:2019-02-20 14:43:44

标签: android kotlin syntax equivalent

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

Boolean mBoolean = false
view.setVisibility(mBoolean ? View.VISIBLE : View.GONE);

3 个答案:

答案 0 :(得分:3)

jq

但是我怀疑在这里使val mBoolean = false view.visibility = if(mBoolean) View.VISIBLE else View.GONE 不可变有任何意义,所以我会选择mBoolean而不是val mBoolean

答案 1 :(得分:0)

您可以通过创建扩展功能扩展到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)

答案 2 :(得分:0)

您还可以使用 when 运算符:

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