Switch in Scala

Switch statements express conditionals across many branches.

Here’s a basic switch.

object SwitchExample extends App {
  val i = 2
  print(s"Write $i as ")
  i match {
    case 1 => println("one")
    case 2 => println("two")
    case 3 => println("three")
  }

  val day = java.time.DayOfWeek.from(java.time.LocalDate.now())
  day match {
    case java.time.DayOfWeek.SATURDAY | java.time.DayOfWeek.SUNDAY => println("It's the weekend")
    case _ => println("It's a weekday")
  }

  val t = java.time.LocalTime.now()
  t.getHour match {
    case hour if hour < 12 => println("It's before noon")
    case _ => println("It's after noon")
  }

  def whatAmI(i: Any): Unit = i match {
    case b: Boolean => println("I'm a bool")
    case n: Int => println("I'm an int")
    case _ => println(s"Don't know type ${i.getClass.getSimpleName}")
  }

  whatAmI(true)
  whatAmI(1)
  whatAmI("hey")
}

To run the program, put the code in a file named SwitchExample.scala and use scala to execute it.

$ scala SwitchExample.scala
Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type String

Next example: Arrays.