Kotlin when with multiple outcomes for each case

Viewed 436

I just started learning Kotlin and I don't know to use when properly. When number is 1, the toast is there, but the image (the second 1 case) is not changed. Is there a way to do this with when?

when (number){
    1 -> Toast.makeText(applicationContext,"1",Toast.LENGTH_SHORT).show()
    1 -> imgview.setImageResource(R.drawable.dice_1)
    2 -> Toast.makeText(applicationContext,"SAD",Toast.LENGTH_SHORT).show()
    2 -> imgview.setImageResource(R.drawable.dice_2) 
}
4 Answers

Sure, just wrap each set of statements in curly braces:

when (number){
    1 -> {
        Toast.makeText(applicationContext,"1",Toast.LENGTH_SHORT).show()
        imgview.setImageResource(R.drawable.dice_1)
    }
    2 -> {
        Toast.makeText(applicationContext,"SAD",Toast.LENGTH_SHORT).show()
        imgview.setImageResource(R.drawable.dice_2) 
    }
}

when statement in Kotlin is similar to switch statement in Java. As soon as a matching case is found in the when statement, the control returns from the statement.

So in your code, the first 1 case gets executed and the control returns from the statement so it never goes to the second 1 case. I don't know your purpose for duplicating these cases instead of grouping them as shown in the below code:

when (number){
    1 -> { 
     Toast.makeText(applicationContext,"1",Toast.LENGTH_SHORT).show()
     imgview.setImageResource(R.drawable.dice_1)
     } 
    2 -> { 
     Toast.makeText(applicationContext,"SAD",Toast.LENGTH_SHORT).show()     
     imgview.setImageResource(R.drawable.dice_2)
     } 
}
    when (number){
        1 -> { 
        Toast.makeText(applicationContext,"1",Toast.LENGTH_SHORT).show()
        imgview.setImageResource(R.drawable.dice_1)}
        2 ->{ Toast.makeText(applicationContext,"SAD",Toast.LENGTH_SHORT).show()
        imgview.setImageResource(R.drawable.dice_2) }
       else->{
       //if both fail to mach
          }
}

Add curly braces to define scope.

when looks for the first condition that matches, so once you hit the first 1 branch, it executes the code and then exits the block. It doesn't fall through to the others - you can think of it like a big if/else if/else if/else block, where the later ones can only trigger if nothing before them did.

So you need to execute all your code in the first branch that matches, like the other answers are showing!

Related