Scala学习笔记-07-模式匹配 - match case语句

↘锁芯ラ 提交于 2020-02-14 01:04:19

case中的通配符 _ 相当于java中的default分支

match结构中不需要break语句来跳出判断,scala会从前往后匹配,一旦配到一个分支即停止

  • 匹配字符:
import scala.io.StdIn._
println("Please input the score Level: ")
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 !")
}
  •  匹配字符串
import scala.io.StdIn._


val country = readLine("please input your country: ")

country match {
	case "中国" => println("you are from China")
	case "美国" => println("youa are from USA")
	case "日本" => println("you are from Japan")
	case _ => println("country input wrong!") 
}
  •  匹配类型
val list1 = List(1,2L,3.3f,"HUAHUA")

for(i <- list1){
	val str = i match {
		case i:Int => "Int value"
		case l:Long => "Long value"
		case f:Float => "Fload value"
		case s:String => "String value"
		case _ => "unexpected value"
	}
	println(i + " is " + str)
}
  •  guard类型
for (i <- (1 to 10).toList){
	i match {
		case _ if(i % 2 == 0) => println(i + " is even number")
		case _ => println(i + " is odd number")
	}
}
  •  case class 类型
case class Car(brand:String, price:Int)

for(car <- List(Car("BYD",8000),Car("BMW",9000),Car("BENZ",11000))){
	car match {
		case Car("BYD",8000) => println("Hello BYD")
		case Car("BMW",9000) => println("Hello BMW")
		case Car(brand,price) => println("Brand: " + brand + ", Price: " + price + ", you want it ?")
	}
}
    • 每一个case子句中的Car(…),都会自动调用Car.unapply(car),并将提取到的值与Car后面括号里的参数进行一一匹配比较。
    • 第一个case和第二个case是与特定的值进行匹配。
    • 第三个case由于Car后面跟的参数是变量,因此将匹配任意的参数值。

 

 

-----

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!