Scala模式匹配
- match语句
- case类
模式匹配的实例(Char):
import scala.io.StdIn._
object TestMatch {
def main(args: Array[String]): Unit = {
println("Please input the score:")
val grade=readChar()
grade match {
case'A'=>println("85-100")
case'B'=>println("70-84")
case'C'=>println("60-69")
case'D'=>println("<60")
case _=>println("error input!")
}
}
}
模式匹配的实例(Line):
import scala.io.StdIn.readChar
object TestMatch2 {
def main(args: Array[String]): Unit = {
println("Please input the score:")
val country=readLine()
country match {
case "China"=>println("中国")
case "America"=>println("美国")
case "Japan"=>println("日本")
case _=>println("我不认识!")
}
}
}
模式匹配的实例(所有值匹配):
object TestMatch3 {
def main(args: Array[String]): Unit = {
for (elem <- List(6, 9, 0.618, "Spark", "Hadoop", 'Hello)) {
val str = elem match {
case i: Int => i + "is an int value." //匹配整形的值,并赋值给i
case d: Double => d + "is a double value." //匹配浮点型的值
case "Spark" => "Spark is found." //匹配特定的字符串
case s: String => s + "is a string value." //匹配其它字符串
case _ => "unexpected value: " + elem //与以上都不匹配
}
println(str)
}
}
}
out:
6is an int value.
9is an int value.
0.618is a double value.
Spark is found.
Hadoopis a string value.
unexpected value: 'Hello
match语句支持case中添加守卫(guard):
object TestMatch4 {
def main(args: Array[String]): Unit = {
for (elem <- List(1, 2, 3, 4)) {
elem match {
case _ if (elem % 2 == 0) => println(elem + " is even.")
case _ => println(elem + " is odd.")
}
}
}
}
out:
1 is odd.
2 is even.
3 is odd.
4 is even.
apply和unapply自动生成调用:
case class Car5(brand: String, price: Int)
object Car5_t {
def main(args: Array[String]): Unit = {
val myBYDCar = Car5("BYD", 89000)
val myBMWCar = Car5("BMW", 1200000)
val myBenzCar = Car5("Benz", 1500000)
for (car <- List(myBYDCar, myBMWCar, myBenzCar)) {
car match {
case Car5("BYD", 89000) => println("Hello,BYD!")
case Car5("BMW", 1200000) => println("Hello,BMW!")
case Car5(brand, price) => println("Brand:" + brand + ",Price:" + price + ",do you want it?")
}
}
}
}
out:
Hello,BYD!
Hello,BMW!
Brand:Benz,Price:1500000,do you want it?
以上代码相当于自动生成了如下内容
def apply(brand: String, price: Int) = new Car5(brand, price)
def unapply(c: Car5): Option[(String, Int)] = Some((c.brand, c.price))