221

How to implement equivalent of following Java switch statement code in Kotlin?

switch (5) {
    case 1:
    // Do code
    break;
    case 2:
    // Do code
    break;
    case 3:
    // Do code
    break;
}
Ryan M
  • 18,333
  • 31
  • 67
  • 74
Mayur Dabhi
  • 3,607
  • 2
  • 14
  • 25

10 Answers10

349

You could do like this:

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

extracted from official help

navylover
  • 12,383
  • 5
  • 28
  • 41
48

switch in Java is effectively when in Kotlin. The syntax, however, is different.

when(field){
    condition -> println("Single call");
    conditionalCall(field) -> {
        print("Blocks");
        println(" take multiple lines");
    }
    else -> {
        println("default");
    }
}

Here's an example of different uses:

// This is used in the example; this could obviously be any enum. 
enum class SomeEnum{
    A, B, C
}
fun something(x: String, y: Int, z: SomeEnum) : Int{
    when(x){
        "something" -> {
            println("You get the idea")
        }
        else -> {
            println("`else` in Kotlin`when` blocks are `default` in Java `switch` blocks")
        }
    }

    when(y){
        1 -> println("This works with pretty much anything too")
        2 -> println("When blocks don't technically need the variable either.")
    }

    when {
        x.equals("something", true) -> println("These can also be used as shorter if-statements")
        x.equals("else", true) -> println("These call `equals` by default")
    }

    println("And, like with other blocks, you can add `return` in front to make it return values when conditions are met. ")
    return when(z){
        SomeEnum.A -> 0
        SomeEnum.B -> 1
        SomeEnum.C -> 2
    }
}

Most of these compile to switch, except when { ... }, which compiles to a series of if-statements.

But for most uses, if you use when(field), it compiles to a switch(field).

However, I do want to point out that switch(5) with a bunch of branches is just a waste of time. 5 is always 5. If you use switch, or if-statements, or any other logical operator for that matter, you should use a variable. I'm not sure if the code is just a random example or if that's actual code. I'm pointing this out in case it's the latter.

Zoe
  • 27,060
  • 21
  • 118
  • 148
47

The switch case is very flexible in kotlin

when(x){

    2 -> println("This is 2")

    3,4,5,6,7,8 -> println("When x is any number from 3,4,5,6,7,8")

    in 9..15 -> println("When x is something from 9 to 15")

    //if you want to perform some action
    in 20..25 -> {
                 val action = "Perform some action"
                 println(action)
    }

    else -> println("When x does not belong to any of the above case")

}
Watercayman
  • 7,970
  • 10
  • 31
  • 49
Himanshu Garg
  • 521
  • 5
  • 3
22

When Expression

when replaces the switch operator of C-like languages. In the simplest form it looks like this

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

when matches its argument against all branches sequentially until some branch condition is satisfied. when can be used either as an expression or as a statement. If it is used as an expression, the value of the satisfied branch becomes the value of the overall expression. If it is used as a statement, the values of individual branches are ignored. (Just like with if, each branch can be a block, and its value is the value of the last expression in the block.)

From https://kotlinlang.org/docs/reference/control-flow.html#when-expression

Pang
  • 9,564
  • 146
  • 81
  • 122
15

when defines a conditional expression with multiple branches. It is similar to the switch statement in C-like languages. Its simple form looks like this.

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

when matches its argument against all branches sequentially until some branch condition is satisfied.

when can be used either as an expression or as a statement. If it is used as an expression, the value of the first matching branch becomes the value of the overall expression. If it is used as a statement, the values of individual branches are ignored. Just like with if, each branch can be a block, and its value is the value of the last expression in the block.

 import java.util.*

fun main(args: Array<String>){
    println("Hello World");

    println("Calculator App");

    val scan=Scanner(System.`in`);

    println("""
        please choose Your Selection to perform
        press 1 for addition
        press 2 for substraction
        press 3 for multipication
        press 4 for divider
        press 5 for divisible
        """);

    val opt:Int=scan.nextInt();

    println("Enter first Value");
    val v1=scan.nextInt();
    println("Enter Second Value");
    val v2=scan.nextInt();

    when(opt){

        1->{
            println(sum(v1,v2));
        }

        2->{
            println(sub(v1,v2));
        }

        3->{
            println(mul(v1,v2));
        }

        4->{
            println(quotient(v1,v2));
        }

        5->{
            println(reminder(v1,v2));
        }

        else->{
            println("Wrong Input");
        }

    }


}


fun sum(n1:Int,n2:Int):Int{
    return n1+n2;
}

fun sub(n1:Int, n2:Int):Int{
    return n1-n2;
}

fun mul(n1:Int ,n2:Int):Int{
    return n1*n2;
}

fun quotient(n1:Int, n2:Int):Int{
    return n1/n2;
}

fun reminder(n1:Int, n2:Int):Int{
    return n1%n2;
}
Suresh B B
  • 1,387
  • 11
  • 13
8

Just use the when keyword. If you want to make a loop, you can do like this:

var option = ""
var num = ""

    while(option != "3") {
        println("Choose one of the options below:\n" +
                "1 - Hello World\n" +
                "2 - Your number\n" +
                "3 - Exit")

        option = readLine().toString()

// equivalent to switch case in Java //

        when (option) {
            "1" -> {
                println("Hello World!\n")
            }
            "2" -> {
                println("Enter a number: ")
                num = readLine().toString()

                println("Your number is: " + num + "\n")
            }
            "3" -> {
                println("\nClosing program...")
            }
            else -> {
                println("\nInvalid option!\n")
            }
        }
    }
Grandtour
  • 1,127
  • 1
  • 11
  • 28
7

In kotlin, their is no switch-case statement. But we have when expression similar to switch. Just like if-else or switch, first all conditions are checked, if none matches then else code evaluated.

when (n) {
    1 -> {
        print("First")
        // run your code
    }
    2 -> print("Second")
    3, 4 -> print("Third or Forth") // check multiple conditions for same code
    in 1..100 -> print("Number is in the range")
    else -> {
        print("Undefined")
    }
}

There is no need of any break as of switch case.

Samiya Khan
  • 241
  • 3
  • 4
5
        val operator = '+'
        val a = 6
        val b = 8

        val res = when (operator) {
            '+' -> a + b
            '-' -> a - b
            '*' -> a * b
            '/' -> a / b
            else -> 0
        }
        println(res);

We use the following code for common conditions

        val operator = '+'
        val a = 6
        val b = 8

        val res = when (operator) {
            '+',
            '-' -> a - b
            '*',
            '/' -> a / b
            else -> 0
        }
        println(res);
Diako Hasani
  • 1,384
  • 13
  • 14
2

Here is an example to know Using “when” with arbitrary objects,

VehicleParts is a enum class with four types.

mix is a method which accepts two types of VehicleParts class.

setOf(p1, p2) - Expression can yield any object

setOf is a kotlin standard library function that creates Set containing the objects.

A set is a collection for which the order of items does not matter. Kotlin is allowed to combine different types to get mutiple values.

When I pass VehicleParts.TWO and VehicleParts.WHEEL, I get "Bicycle". When I pass VehicleParts.FOUR and VehicleParts.WHEEL, I get "Car".

Sample Code,

enum class VehicleParts {
TWO, WHEEL, FOUR, MULTI
}

fun mix(p1: VehicleParts, p2: VehicleParts) =
when (setOf(p1, p2)) {

    setOf(VehicleParts.TWO, VehicleParts.WHEEL) -> "Bicycle"

    setOf(VehicleParts.FOUR, VehicleParts.WHEEL) -> "Car"

    setOf(VehicleParts.MULTI, VehicleParts.WHEEL) -> "Train"
    else -> throw Exception("Dirty Parts")

}

println(mix(VehicleParts.TWO,VehicleParts.WHEEL))
Manikandan
  • 690
  • 5
  • 5
0

If You want to print or open multiple Activities using switch case (When) in Kotlin then use this code.. Thank you..

var dataMap: Map<String?, String?> = HashMap() var noteType: String? = ""

when (noteType) {
        "BIGTEXT" -> NEW_PAGE(dataMap)
        "NORMAL" -> NORMAL_PAGE(dataMap)
        "ABOUT"->ABOUT_PAGE((dataMap))

    }
  • Not gonna lie, thought just having multiple activity application was horrible enough, turns out you can take it to another level – JustSightseeing Nov 29 '22 at 00:14
  • I make correction in my code check it once again – Ankit Tiwari Nov 29 '22 at 09:26
  • @AnkitTiwari he mean that new pages for different sizes of text is bad idea, you need to change text size it on the fly using `textSize` method or similar approach instead of create new page or activity for it – Acuna May 09 '23 at 00:19