How to make a switch in kotlin

2

I have the following example switch in java:

int variable = 2;

switch(variable){
     case 1:
     //cosas
     break;

     case 2:
     case 3:
        break;
     case 4:
     //cosas
     break

    default:
    break;
}

What I want with this java code is to do it in kotlin, that is to say that when the variable is 2 or 3 it executes the same, just like I did in java.

    
asked by Gustavo Mora 21.11.2017 в 20:04
source

4 answers

2

Review the documentation , When , replaces the switch operator of type C languages, in this case Kotlin . Example:

when (x) {
    1 -> print("x == 1")
    2 -> print("x == 2")
    else -> { // Note the block
        print("x no es 1 o 2")
    }
}

If many cases should be handled in the same way, the conditions can be combined with a comma:

when (x) {
    0, 1 -> print("x == 0 or x == 1")
    else -> print("de otra forma.")
}

We can use arbitrary expressions (not just constants) as branch conditions

when (x) {
    parseInt(s) -> print("s codifica x")
    else -> print("s no codifica a x")
}

We can also verify a value that can be in or ! in within a range or collection:

when (x) {
    in 1..10 -> print("x is in the range")
    in validNumbers -> print("x is valid")
    !in 10..20 -> print("x is outside the range")
    else -> print("none of the above")
}

Having defined the above, the version of your code in Kotlin would be :

   var variable = 2

    when (variable) {
        1 -> {
            //Agrega aquí lo que realizaría si variable es igual 1

        }
        2, 3 -> {
            //Agrega aquí lo que realizaría si variable es igual a 2 o 3

        }
        4 -> {
            //Agrega aquí lo que realizaría si variable es igual 4

        } 
        else -> { // Opción default

        }
    }
    
answered by 21.11.2017 / 20:10
source
2

In Kotlin the word 'when' is used

when (variable) {
    1 -> break
    2,3 -> break
    4 -> break
    else -> { break
    }
}
    
answered by 21.11.2017 в 20:07
1

In kotlin there is no control called switch but when :

when (x) {
    1 -> print("x == 1")
    2 -> print("x == 2")
    else -> { // Note the block
        print("x is neither 1 nor 2")
    }
}

when also accepts expressions:

when(x)
{
  is String -> { }
  0, 1 -> // si es igual 0 o 1 
  else -> { }
}
    
answered by 21.11.2017 в 20:08
0

You can use it in two ways:

1. When your cases only have one procedure.

var variable=2
when (variable) {
1 -> print("No Existe")
2 -> print("Existe")
3 -> print("No Existe")
4 -> print("No Existe")
else -> print("Error")
}

2. If your cases have more than one procedure.

var variable=2

when (variable) {
1 -> {
      print("No Existe")
     }
2 -> {
      print("Existe")
     }
3 -> {
      print("No Existe")
     }
4 -> {
      print("No Existe")
      }
else -> {
    print("Error")
}
}

Note: If your cases have more procedures you should use {} if not nothing.

    
answered by 27.02.2018 в 17:10