Sacla中的模式匹配
基本语法
Scala中的模式匹配:
用于替代传统C/C++/Java的switch-case结构,但补充了更多功能,拥有更强的能力。
语法:
value match {
case caseVal1 => returnVal1
case caseVal2 => returnVal2
...
case _ => defaultVal
}
下面所有的匹配规则,都可以添加条件守卫
模式匹配支持类型:所有类型字面量,包括字符串、字符、数字、布尔值、甚至数组列表等。
常用的匹配规则示例
1)内容匹配
def judgeFun(grade:String, name:String) = {
grade match {
case "A" => println("考得特别棒!90分以上的")
case "B" => println("考得还可以!80-90分的")
case "C" => println("需要加油哦!60-80分的")
case _ if name == "Scala" => println("这个没成绩,但是是个学霸") // 在判断中添加守卫,就是添加判断
case _ => println("其他的人考得太差了,没成绩")
}
}
// 函数调用:
judgeFun("A","Java")
judgeFun("F","Scala")
judgeFun("F","Oracle")
2)类型匹配
def typeMathFun(obj:Any) = {
obj match {
case x:Int => println("Int")
case x:String => println("String")
case x:Map[_,_] => println("Map")
//.... 没有写完的类型,可以自己补充
case _ => println("不识别的类型")
}
}
// 函数调用:
typeMathFun(1)
typeMathFun("Maggie")
typeMathFun(Map("Scala"->"BigData"))
typeMathFun(true)
- 也可以在匹配了类型后,对各个值进行再计算。
def typeMath() = {
val inputs = Array(1,20,"PK", true, 'A')
1.to(10).map(x=>{ // 循环10次,随机得到结果
inputs(Random.nextInt(inputs.length)) match {
case t:Int if t < 15 => println( t * 8)
case t:Int => println( t + 3)
case t:String => println( t.toUpperCase)
case t:Boolean => println( t )
case _ => println("不识别的类型")
}
})
}
// 函数调用:
typeMath()
3)Array集合匹配
def ArrayMathFun(array:Array[String]) ={
array match {
case Array("Scala") => println("只有一个Scala小伙伴")
case Array(x, y) => println(s"只有两个小伙伴,x = $x, y = $y")
case Array("3",_*) => println("以3开头的Array都符合标准")
case _ =>println("其他都不符合标准")
}
}
// 函数调用:
ArrayMathFun(Array("2","3"))
ArrayMathFun(Array("3"))
ArrayMathFun(Array("3","2","13"))
ArrayMathFun(Array("Scala","2","13"))
/**
* 只有一个Scala小伙伴
* 只有两个小伙伴,x = 2, y = 3
* 以3开头的Array都符号标准
* 以3开头的Array都符号标准
* 其他都不符合标准
*/
def ArrayIntMathFun(array:Array[Int]) ={
array match {
case Array(1,2,a,b) => println(s"Array(1,2,a,b), 其中 a = $a, b = $b")
case Array(1,a@_*) => println(s"Array(1,a_*),a 原来的值: $a, a = ${a.toList}")
case _ =>println("其他都不符合标准")
}
}
// 函数调用:
ArrayIntMathFun(Array(1,2,3,5))
ArrayIntMathFun(Array(1,6,7,8,9))
ArrayIntMathFun(Array(4,3,2))
/**
* Array(1,2,a,b), 其中 a = 3, b = 5
* Array(1,a_*),a 原来的值: Vector(6, 7, 8, 9), a = List(6, 7, 8, 9)
* 其他都不符合标准
*/
4)Tuple集合匹配
def tupleMathFun() ={
val tuple = ("Maggie", 18)
tuple match {
case (name, age) => println(s"$name ==> $age")
}
}
// 函数调用:
tupleMathFun() // 输出结果: Maggie ==> 18
5)List集合匹配
def ListMathFun(list:List[String]) ={
list match {
case "Scala"::Nil => println("只有一个Scala的List")
case x::y::Nil => println(s"List只有两个小伙伴,x = $x, y = $y")
case "3"::tail => println("以3开头的List集合")
case _ =>println("其他都不符合标准")
}
}
ListMathFun(List("Scala"))
ListMathFun(List("2","3"))
ListMathFun(List("3"))
ListMathFun(List("3","2","13"))
ListMathFun(List("Scala","2","13"))
/**
* 只有一个Scala的List
* List只有两个小伙伴,x = 2, y = 3
* 以3开头的List集合
* 以3开头的List集合
* 其他都不符合标准
*/
6)自定义类&case class匹配
–
class Person(val name:String,val age:Int)
object Person {
// 需要出创建一个Person的提取器unapply。
def unapply(person: Person): Option[(Any, Any)] = {
if(null != Person){
Some(person.name,person.age)
}else{
None
}
}
}
val person = new Person("张三丰", 25)
// class匹配,其实底层调用的class的伴生对象的unapply 【不建议使用,比较麻烦】
person match {
case Person(name, age) => println(s"$name ==> $age")
}
- case Class 代替上面例子中的class
println("===========case Class 代替上面例子中的class====")
case class User(name:String,age:Int)
val user = new User("肖战",23)
user match {
case User(name, age) => println(s"$name ==> $age")
}
7)Option匹配
val grades = Map("scala"->"A","Java"->"B","PHP"->"C")
def getGrade(name:String) = {
val gradeValue = grades.get(name)
gradeValue match {
case Some(gradeValue) => println(gradeValue)
case None => println("没找到")
}
}
getGrade("scala")
getGrade("Java")
getGrade("C#")
8)文件资源/URL资源匹配
def readLine(sourceLines: BufferedSource) ={
for(ele <- sourceLines.getLines()){
println(ele)
}
}
// 读取文件资源
lazy val fileSource: BufferedSource = Source.fromFile("data/word.md")
readLine(fileSource)
println("===================================")
// 读取URL资源
val urlSource: BufferedSource = Source.fromURL("http://www.baidu.com")
readLine(fileSource)
优秀的笔记推荐:
1)https://github.com/tch0/notes/blob/master/Scala.md#%E6%A8%A1%E5%BC%8F%E5%8C%B9%E9%85%8D
2)https://blog.csdn.net/qq_55906442/article/details/127518131