shortTitle | shortDescription | scastieUrl |
---|---|---|
Pattern Matching |
Think “switch” on steroids. Match against class hierarchies, sequences, constants and more. |
In Scala, case classes are used to represent structural data
types. They implicitly equip the class with meaningful toString
,
equals
and hashCode
methods, as well as the
ability to be deconstructed with pattern matching.
In this example, we define a small set of case classes that represent binary
trees of integers (the generic version is omitted for simplicity here).
In inOrder
, the match
construct chooses the right
branch, depending on the type of t
, and at the same time
deconstructs the arguments of a Node
.
<div class="scala-code">
<div class="code-element dark">
<div class="bar-code"><span>Pattern matching</span></div>
<pre><code>// Define a set of case classes for representing binary trees.
sealed abstract class Tree case class Node(elem: Int, left: Tree, right: Tree) extends Tree case object Leaf extends Tree
// Return the in-order traversal sequence of a given tree. def inOrder(t: Tree): List[Int] = t match { case Node(e, l, r) => inOrder(l) ::: List(e) ::: inOrder(r) case Leaf => List() }
</div>