← Back to Scala Course | Chapter 10: Pattern Matching | Lesson 2 of 7

Matching Types

In this page:

  1. Matching Types

Matching Types

A case variableName: Type => pattern matches based on the runtime type of a value, binding it to a new variable of that specific type inside the branch. This is Scala's structured alternative to manual isInstanceOf/asInstanceOf type checks and casts. It's especially useful when a value's static type is a broad supertype but you need to handle several possible concrete subtypes differently.

Note: case s: String => ... both checks the type and gives you a properly-typed variable s to use inside that branch.

Example: Matching Types

markup
object Main extends App {
  def describe(x: Any): String = x match {
    case i: Int => s"An Int: $i"
    case s: String => s"A String of length ${s.length}"
    case _ => "Something else"
  }

  println(describe(42))
  println(describe("hello"))
  println(describe(3.14))
}
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.