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:
Syntax
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
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))
}
Login to try C/C++/Java/PHP code in the editor
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
- Matching on generic types like
case l: List[Int] =>, which is unchecked because type arguments are erased at runtime. - Using
isInstanceOfand casting withasInstanceOfinstead of a type pattern, which is longer and less safe. - Ordering
case _: Anybefore 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: