Kotlin uses when
instead of switch
and it looks something like this:
when(version) {
"v1" ->
Log.d("TAG", "WOW")
"v2" ->
Log.d("TAG", WOAAH")
else ->
"Log.d("TAG", "ELSE")
So far so good. But what if I want to add several lines of code after each conditional? This is my code, and I have tried using and
at the end of each new line:
when(version) {
"anhorig" ->
Log.d("TAG", "Anhorig") and
subHeader.text = getString(R.string.sv_anhorig_ch1)
"personal" ->
Log.d("TAG", "Personal")
else ->
Log.d("TAG", "Else")
}
I get an error on line
subHeader.text = getString(R.string.sv_anhorig_ch1)
saying Type mismatch. Expected Int, found string and Unit
The code line works fine if separated from the when
code. What am I doing wrong?
You need to surround your multiple lines of code in a block, like so:
when(version) {
"anhorig" -> {
Log.d("TAG", "Anhorig")
subHeader.text = getString(R.string.sv_anhorig_ch1)
}
"personal" ->
Log.d("TAG", "Personal")
else ->
Log.d("TAG", "Else")
}
As for the type mismatch, the value of the when expression is equal to the last evaluated statement within the block. It seems like the expected value of this expression is Int, but your last statement is subHeader.text = getString(R.string.sv_anhorig_ch1)
which is string.
You can read more in the Kotlin documentation for when expressions.
When a case of a when
statement is more than one line, you should use the block of code in braces {}
. Like this:
when(version) {
"anhorig" -> {
Log.d("TAG", "Anhorig")
subHeader.text = getString(R.string.sv_anhorig_ch1)
}
"personal" ->
Log.d("TAG", "Personal")
else ->
Log.d("TAG", "Else")
}
And of course you should remove and
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With