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

Matching Types

Matching on types checks what kind of thing a value is and reacts accordingly, like a mail sorter looking at whether it is a letter or a parcel. Each case names a type.

In this page:

  1. Matching Types
Syntax
scala
value match {
  case x: Int    => expression
  case s: String => expression
  case _         => default_result
}

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))
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Matching on generic types like case l: List[Int] =>, which is unchecked because type arguments are erased at runtime.
  2. Using isInstanceOf and casting with asInstanceOf instead of a type pattern, which is longer and less safe.
  3. Ordering case _: Any before more specific types, so the specific cases are never reached.
🔒

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.