Marzadmz Marzadmz - 3 years ago 306
Android Question

How to convert if expression to when in Kotlin

How can I convert the following code from

if expression
to
when
by using Kotlin?

Actually i'm using 2 adapters inside my Activity and i got problem will converting
if expression
to
when
, any solution?

Here is my code

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
}

Answer Source

Something like this:

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
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download