0Pricing
Scala for Backend Engineering & Functional Programming · Lesson

Matching Types and Values

Type patterns.

Type Patterns

Beyond matching literal values, match can branch on the type of a value. This is called a type pattern.

You write case x: Type => and the branch runs when the value is of that type, binding it to x.

Matching by Type

When a value has a general type like Any, you can discover its concrete type with a type pattern.

Each case x: T checks the runtime type.

object Main {
  def describe(x: Any): String = x match {
    case i: Int    => "an Int"
    case s: String => "a String"
    case _         => "something else"
  }
  def main(args: Array[String]): Unit = {
    println(describe(5))
    println(describe("hi"))
    println(describe(3.14))
  }
}

All lessons in this course

  1. match Expressions
  2. Matching Types and Values
  3. Guards and Binding
  4. Deconstruction
← Back to Scala for Backend Engineering & Functional Programming