模式匹配类型
模式匹配也可用于检查实例的类型,而不是使用 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?'
请注意,在 Foo
和 Woo
的情况下,我们使用下划线(_
)来匹配未绑定的变量。也就是说,值(在这种情况下分别为 Hadas
和 27
)未绑定到名称,因此在该情况的处理程序中不可用。这是有用的简写,以匹配任何值而不用担心该值是什么。