Kotlin when with multiple values not working when value is an android view
AndroidKotlinAndroid 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)
}
}
}