Kotlin when with multiple values not working when value is an android view

AndroidKotlin

Android Problem Overview


I implemented a function that is used in anko's apply recursively:

fun applyTemplateViewStyles(view: View) {
    when(view) {
        is EditText, TextView -> {
            ....
        }
    }
}

And I receive an error saying that "Function invocation 'TextView(...)' expected"

Since I can write an when with a clause like is 0, 1, why I can't do the same with an Android View?

Android Solutions


Solution 1 - Android

You're missing the other is:

fun applyTemplateViewStyles(view: View) {
    when(view) {
        is EditText, is TextView -> {
            println("view is either EditText or TextView")
        }
        else -> {
            println("view is something else")
        }
    }
}

Solution 2 - Android

You can do this, you just didn't get the syntax right. The following works for handling multiple types under one branch of when:

when(view) {
    is EditText, is TextView -> {
        ....
    }
}

Solution 3 - Android

In case of multiple text option handling you can use comma

when(option) { //option is string
    "type A","type B" -> {
        ....
    }
}

Solution 4 - Android

Use comma-separated to handle multiple options for the same execution.

{ 
view ->
   when(view.id) {
       homeView.tv_new_dealer_rank_to_achieve.id,
       homeView.tv_sales_rank_to_achieve.id,
       homeView.tv_payment_rank_to_achieve.id,
       homeView.tv_bill_dealer_rank_to_achieve.id -> {
           homePresenter.reDirectToFragment(10)
       }
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjonathanrzView Question on Stackoverflow
Solution 1 - AndroidDaniel StormView Answer on Stackoverflow
Solution 2 - Androidzsmb13View Answer on Stackoverflow
Solution 3 - AndroidUmasankarView Answer on Stackoverflow
Solution 4 - AndroidBharat LalwaniView Answer on Stackoverflow