tore
tore

Reputation: 689

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?

Upvotes: 9

Views: 8539

Answers (2)

Demigod
Demigod

Reputation: 5635

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

Upvotes: 1

Dehodson
Dehodson

Reputation: 459

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.

Upvotes: 17

Related Questions