Scala模式匹配类型
示例
模式匹配也可以用于检查实例的类型,而不是使用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
这样,它类似于经典的“switch”语句,但没有掉线功能。但是,您也可以从相关类型中对匹配和“提取”值进行模式化。例如:
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 + " 优雅!" case Foo(_) => "有人很聪明!" case Woo(s, _) => s + " 冒险!" case _ => "What are we talking about?" } } print(matcher(Foo("Diana"))) // prints 'Diana 优雅!' print(matcher(Bar("Hadas"))) // prints '有人很聪明!' print(matcher(Woo("Beth", 27))) // prints 'Beth 冒险!' print(matcher(Option("Katie"))) //打印“我们在说什么?”
请注意,在FooandWoo情况下,我们使用下划线(_)来“匹配未绑定的变量”。也就是说,值(在这种情况下,分别为Hadas和27)未绑定到名称,因此在该情况下的处理程序中不可用。这是有用的速记,用于匹配“任何”值而不用担心该值是什么。