logo

Scala - Pattern Matching

  • first match
  • no fall through
  • each case is followed by a function: case Pattern => Body
  • _ as default, always the last one
scala> val point = Array(x, y, z)
point: Array[Int] = Array(1, 2, 3)

scala> val Array(x, _*) = point
x: Int = 1

scala> val Array(x, xs @ _*) = point
x: Int = 1
xs: Seq[Int] = Vector(2, 3)
object MatchTest1  {
  def toString(x: Int): String = x match {
    case 1 => "one"
    case 2 => "two"
    case _ => "many"
  }

  def main(args: Array[String]) = {
    println(toString(1))
    println(toString(2))
    println(toString(3))
  }
}
$ scala test.scala
one
two
many

To use value from a val or var, use the backquote(`):

object MatchTest1  {
  def toString(x: Int): String = {
    val special = 100
    x match {
      case 1 => "one"
      case 2 => "two"
      case `special` => "something special"
      case _ => "many"
    }
  }

  def main(args: Array[String]) = {
    println(toString(1))
    println(toString(2))
    println(toString(100))
    println(toString(101))
  }
}

Run the code:

$ scala test.scala
one
two
something special
many
object MatchTest1  {
  def testType(x: Any): String = {
    x match {
      case y:Int => "is Int"
      case z:String => "is String"
    }
  }

  def main(args: Array[String]) = {
    println(testType("1"))
    println(testType(1))
    println(testType(1.0))
  }
}

Run the code:

$ scala test.scala
is String
is Int
scala.MatchError: 1.0 (of class java.lang.Double)
	at Main$.testType(test.scala:3)
	at Main$.main(test.scala:12)
	at Main.main(test.scala)