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
- match Expressions
- Matching Types and Values
- Guards and Binding
- Deconstruction