如何使用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
}
答案 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
}