scala中ca的⽤法scala中没有switch,但是有ca,其ca相当强⼤,有各种不同的匹配⽅式。
⼀.简单匹配,值匹配:
例 a:
val bools = List(true, fal)
for (bool <- bools) {
bool match {
ca true => println("heads")
ca fal => println("tails")
ca _ => println("something other than heads or tails (yikes!)")
三节三爱
}
}
例 b:
防欺凌import scala.util.Random
val randomInt = new Random().nextInt(10)
randomInt match {
ca 7 => println("lucky ven!")
ca otherNumber => println("boo, got boring ol' " + otherNumber)
}
⼆. 类型匹配
例a:
val sundries = List(23, "Hello", 8.5, 'q')
for (sundry <- sundries) {
sundry match {
ca i: Int => println("got an Integer: " + i)
ca s: String => println("got a String: " + s)
ca f: Double => println("got a Double: " + f)
ca other => println("got something el: " + other)
}
}
三 根据顺序匹配
val willWork = List(1, 3, 23, 90)
val willNotWork = List(4, 18, 52)
val empty = List()
for (l <- List(willWork, willNotWork, empty)) {
l match {
ca List(_, 3, _, _) => println("Four elements, with the 2nd being '3'.")
蔡伟民ca List(_*) => println("Any other list with 0 or more elements.")
}
}
四 ca⾥⾯⽤ guard 的数组匹配:
val tupA = ("Good", "Morning!")
val tupB = ("Guten", "Tag!")
for (tup <- List(tupA, tupB)) {
tup match {
ca (thingOne, thingTwo) if thingOne == "Good" =>
形态万千println("A two-tuple starting with 'Good'.")
ca (thingOne, thingTwo) =>println("This has two things: " + thingOne + " and " + thingTwo) }
}
五 对象深度匹配:
ca class Person(name: String, age: Int)
语文课程与教学论val alice = new Person("Alice", 25)
val bob = new Person("Bob", 32)
val charlie = new Person("Charlie", 32)
for (person <- List(alice, bob, charlie)) {
person match {
ca Person("Alice", 25) => println("Hi Alice!")
ca Person("Bob", 32) => println("Hi Bob!")
咏雪古诗ca Person(name, age) =>
北京麻将println("Who are you, " + age + " year-old person named " + name + "?")
}
}
六 正则表达式匹配:
val BookExtractorRE = """Book: title=([^,]+),\s+authors=(.+)""".r
val MagazineExtractorRE = """Magazine: title=([^,]+),\s+issue=(.+)""".r
val catalog = List(
"Book: title=Programming Scala, authors=Dean Wampler, Alex Payne",
"Magazine: title=The New Yorker, issue=January 2009",
"Book: title=War and Peace, authors=Leo Tolstoy",
"Magazine: title=The Atlantic, issue=February 2009",
"BadData: text=Who put this here??"
)
个人工作特点for (item <- catalog) {
item match {
ca BookExtractorRE(title, authors) =>
println("Book \"" + title + "\", written by " + authors)
ca MagazineExtractorRE(title, issue) =>
println("Magazine \"" + title + "\", issue " + issue)
ca entry => println("Unrecognized entry: " + entry)
}
}