Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use multiple lines in Kotlins when switch?

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?

like image 496
tore Avatar asked Oct 04 '18 14:10

tore


2 Answers

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.

like image 113
Dehodson Avatar answered Oct 24 '22 08:10

Dehodson


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

like image 34
Demigod Avatar answered Oct 24 '22 08:10

Demigod