如何将表达式转换为何时在Kotlin中

时间:2017-10-01 23:05:21

标签: android kotlin

如何使用Kotlin将以下代码从if expression转换为when

实际上我在我的Activity中使用了2个适配器,我遇到问题会将if expression转换为when,任何解决方案?

这是我的代码

    var ADAPTER_TYPE_1=adapter1
    var ADAPTER_TYPE_2=adapter2

   if(ADAPTER_TYPE_1 ==lvFoods2.adapter) {
       ADAPTER_TYPE_1 = FoodAdapter(listOfFoods2, this)
       lvFoods2.adapter = ADAPTER_TYPE_1
    } else if (ADAPTER_TYPE_2==lvFoods2.adapter) {
       ADAPTER_TYPE_2 = FoodAdapter2(listOfFoods3, this)
       lvFoods2.adapter = ADAPTER_TYPE_2
     }

1 个答案:

答案 0 :(得分:3)

这样的事情:

var adapterType1 = adapter1
var adapterType2 = adapter2

lvFoods2.adapter = when (lvFoods2.adapter) {
    adapterType1 -> FoodAdapter(listOfFoods2, this).also { adapterType1 = it }
    adapterType2 -> FoodAdapter2(listOfFoods3, this).also { adapterType2 = it }
    else -> lvFoods2.adapter
}