今天繼續來介紹其餘的pattern matching
Constuctor pattern讓我們可以比對建構式,把建構式放到match運算式裡的case語句。
case class Dog(name: String, age: Int)
def test(x: Any) = x match
case Dog("Tom", 4) => "Tom is four years old."
case _ => " "
Sequence pattern讓我們可以依據List, Array, Vector來比對模式
底線符號(_)代表一個元素
_*代表0個或多個元素
def test(x: Any) = x match
case List(1) => "1"
case List(1, 2, 3) => "1 2 3"
case List(1, 2, _) => "1 2 and the other"
case List(1, _*) => "starts with 1, any number of elements"
可以比對元組
def Tupletest(x: Any) =
x match
case (a, b, c) => "matched"
case _ => ""
def test(x: Any) =
x match
case s: String => s"String: $s"
case i: Int => s"Int: $i"