模式匹配型別

模式匹配也可用於檢查例項的型別,而不是使用 isInstanceOf[B]

val anyRef: AnyRef = ""
                                                  
anyRef match {
  case _: Number       => "It is a number"
  case _: String       => "It is a string"
  case _: CharSequence => "It is a char sequence"
}
//> res0: String = It is a string

案件的順序很重要:

anyRef match {
  case _: Number       => "It is a number"
  case _: CharSequence => "It is a char sequence"
  case _: String       => "It is a string"
}
//> res1: String = It is a char sequence

以這種方式,它類似於傳統的切換語句,沒有直通功能。但是,你也可以從相關型別中模式匹配和提取值。例如:

case class Foo(s: String)
case class Bar(s: String)
case class Woo(s: String, i: Int)

def matcher(g: Any):String = {
  g match {
    case Bar(s) => s + " is classy!" 
    case Foo(_) => "Someone is wicked smart!"
    case Woo(s, _) => s + " is adventerous!"
    case _ => "What are we talking about?"
  }
}

print(matcher(Foo("Diana")))  // prints 'Diana is classy!'
print(matcher(Bar("Hadas")))  // prints 'Someone is wicked smart!'
print(matcher(Woo("Beth", 27)))   // prints 'Beth is adventerous!'
print(matcher(Option("Katie")))  // prints 'What are we talking about?'

請注意,在 FooWoo 的情況下,我們使用下劃線(_)來匹配未繫結的變數。也就是說,值(在這種情況下分別為 Hadas27)未繫結到名稱,因此在該情況的處理程式中不可用。這是有用的簡寫,以匹配任何值而不用擔心該值是什麼。