34.scala编程思想笔记——基于类型的模式匹配
欢迎转载,转载请标明出处:blog.csdn.net/notbaron/ar…
源码下载连接请见第一篇笔记。\
可以基于值的模式匹配,还可以按照值的类型来匹配。
例如:
import com.atomicscala.AtomicTest._
def acceptAnything(x:Any):String = {
x match {
cases:String => "A String: " + s
case i:Intif(i < 20) =>
s"AnInt Less than 20: $i"
case i:Int=> s"Some Other Int: $i"
casep:Person => s"A person ${p.name}"
case _=> "I don't know what that is!"
}
}
acceptAnything(5) is
"An IntLess than 20: 5"
acceptAnything(25) is "Some Other Int: 25"
acceptAnything("Some text") is
"A String: Some text"
case class Person(name:String)
val bob = Person("Bob")
acceptAnything(bob) is "A person Bob"
acceptAnything(Vector(1, 2, 5)) is
"I don't know what that is!"
执行如下:
An Int Less than 20: 5
Some Other Int: 25
A String: Some text
A person Bob
I don't know what that is!
其中acceptAnything的参数类型Any.
Any 允许任何类型的参数。
Match表达式会查找String,Int或我们自己的类型Person.
注意下划线作用是通配符,用来匹配任何值都不匹配的对象。