Matching Types
In this page:
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
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: