1.模式匹配基本语法
/**变量 match {
case 值 =>
匹配后的逻辑
case 值 =>
匹配后的逻辑
}
*/
import scala.io.StdIn
object $01_MatchBasic {
def main(args: Array[String]): Unit = {
val x = StdIn.readLine()
x match {
case "spark" =>
println("输入的是spark")
case "hadoop" =>
println("输入的是hadoop")
case "flume" =>
println("============")
println("输入的是flume")
//case x =>
// println(s"输入的是${x}")
//如果变量不需要在右边使用,则可以用_代替
case _ =>
println(s"输入的是其他字符串")
}
}
}
2.模式守卫
匹配某个范围的数据,可在模式匹配中增加守卫条件
import scala.io.StdIn
object $02_MatchGuard {
/**
* 守卫
* 模式匹配语法:
* 变量 match {
* case 值 if 布尔表达式 =>
* 匹配后的逻辑
* case 值 if 布尔表达式 =>
* 匹配后的逻辑
* }
*
* 模式匹配有返回值
*/
def main(args: Array[String]): Unit = {
val line = StdIn.readLine()
val result = line match {
case x if x.contains("hello") => {
println(s"${x} 包含hello")
10
}
case x if x.contains("spark") =>
println(s"${x} 包含spark")
20
case x =>
println("其他字符串")
30
}
println(result)
}
}
//输出结果
//请输入字符串
//helloworld
//helloworld包含hello
//10
3.模式匹配类型
3.1常量匹配
scala中,模式匹配可以匹配所有的字面量,包括字符串,字符,数字,布尔值等等。
object TestMatchVal {
def main(args: Array[String]): Unit = {
println(describe(6))
}
def describe(x: Any) = x match {
case 5 => "Int five"
case "hello" => "String hello"
case true => "Boolean true"
case '+' => "Char +"
case _=>"your input is wrong"
}
}
//打印结果
//your input is wrong
3.2 类型匹配
import scala.io.StdIn
import scala.util.Random
object $03_MatchValue {
def main(args: Array[String]): Unit = {
val list=List[Any]("hello",10,false,2.2,100)
val value:Any=list(Random.nextInt(list.length))
println(value)
/* value match {
case x:String => println(s"字符串${x}")
case _:Double => println("double")
case _:Boolean => println("boolean")
case _:Int => println("int")
case _ => println("其他类型")
}*/
//***匹配的时候 如果匹配条件中是通过变量匹配***
// 1、如果变量名首字母是小写,则普通变量,后续值会传递给变量
// 即若变量名为abc,输入hello后hello赋值给abc,打印==========hello
// 2、如果变量名首字母是大写,则匹配外部的常量,相当于就是匹配一个具体的值
// 即若变量名为Abc,输入hello后,与Abc的值"hello spark"不匹配,打印*********
val Abc="hello spark"
println("请输入")
val line=StdIn.readLine()
line match{
case Abc if Abc.contains("hello")=>{
println("=========="+Abc)
}
case _=>println("************")
}
val aaa:Int=10
}
}
//打印结果
//false
//boolean
//请输入
//hello abc
//************
3.5 匹配数组
object $04_MatchArray {
def main(args: Array[String]): Unit = {
//val arr = Array[Any] (10,20,30,40)
val arr = Array[Any] (30,"hello",2.2,40)
arr match {
//匹配数组有三个元素
case Array(x,y,z) =>
println(s"数组有三个元素,${x} ${y} ${z}")
//匹配数组首位元素
case Array(10,_*) =>
println("数组首位元素是10,后面的元素不清楚")
case Array(x:Int,y:String,z:Double,_*) =>
println("数组至少有三个元素,分为为int string double类型")
}
/**
* Array[Int] => new Int[]{..}
* Array[Stirng] => new String[]{}
* arr = new Object[]{}
*
* new String[]{}
*/
arr match {
case x:Array[Any] => println("Array[Any]")
}
}
}
//打印结果
//数组最少有三个元素,分别为int string double类型
//Array[Any]
3.6 匹配列表
import scala.collection.immutable.Queue
object $05_MatchList {
def main(args: Array[String]): Unit = {
val list = List("hello",false,2.2,10,30,"hadoop")
/* list match {
case List(x) => println("匹配list只有一个元素,${x}")
case List(x:String,_:Boolean,_*) => println("匹配list至少有两个元素,这两个元素的类型为string boolean")
case List(x,y,z,_*) => println(s"匹配list至少有三个元素 ${x} ${y} ${z}")
case _ => println("其他")
}*/
var n:List[Any] = Nil
n = list
val list2 = 0 :: 10 :: Nil
println(list2)
//打印结果
//List(0, 10)
//val A = List(10,30,"hadoop")
list match{
case x :: Nil => println("匹配list只有一个元素,${x}")
case (x:String) :: (y:Int) :: tail => println(s"匹配至少两个元素,元素类型分别为 string boolean ${tail}")
case x :: y :: z :: abc => println(s"匹配list至少有三个元素 ${x} ${y} ${z} ${abc}")
}
//打印结果 匹配至少两个元素,元素类型分别为 string boolean ${tail}
/**
* 泛型的特性: 泛型擦除
* List[Int] -> new List
*
*/
list match {
case x:List[Int] => println("List[Int]")
case x:List[String] => println("List[String]")
case x:List[Any] => println("List[Any]")
}
//打印结果 List[Int]
val map = Map[String,String]("aa"->"bb")
map match {
case x:Map[String,Int] => println("Map[Int,Int]")
}
//打印结果 Map[Int,Int]
val set = Queue[Any](1,2,3)
set match {
case x:Queue[Int] => println("set[String]")
}
}
}
//打印结果 set[String]
3.7 匹配元组
object $06_MathType {
def main(args: Array[String]): Unit = {
val tuple:(Any,Any,Any) = ("zhangsan",20,"北京")
tuple match {
case (name:String,_:Int,_:String) =>
println(s"${name} string")
case (name,_,_) =>
println(s"name=${name}")
}
//打印结果
//zhangsan String
val school = List(
("北京小学",("小学一班",("1001","zhangsan",20))),
("北京小学",("小学一班",("1002","lisi",22))),
("北京小学",("小学一班",("1003","wangwu",23)))
)
//取出学生的姓名
//val result = school.map(_._2._2._2)
//val reuslt = school.map( line => {
// line match {
// case(schoolName,(className,(sid,sname,age))) => sname
// }
//})
//
val reuslt = school.map {
case (schoolName,(className,(sid,sname,age))) => sname
}
println(reuslt)
}
}
//打印结果
//List(zhangsan, lisi, wangwu)
3.8 匹配对象及样例类
import scala.beans.BeanProperty
object $07_MathObect {
case class Person(@BeanProperty name:String, @BeanProperty age:Int)
trait SEX
case object Man extends SEX
case object Woman extends SEX
/**
* 样例类:
* 语法: case class 类名([val/var] 属性名:属性类型)自动有 @BeanProperty
* 样例对象:
* 语法: case object object名称
*
*
*伴生类:
* class Person(val name:String,val age:Int)
*
* object Person{
* def apply(name:String,age:Int) = new Person(name,age)
* }
*
* Person("zhangsan",20)
*/
def main(args: Array[String]): Unit = {
val person = Person("zhangsan",20)
println(person)
println(person.getName)
//person.age = 100
//println(person)
m1(Man)
person match {
case Person(name,age) =>
println(s"name=${name} age=${age}")
}
val student = new Student("lisi",100)
student match {
/* case x:Student =>
println(s"x=${x.name}")*/
case Student(name,age) =>
println(s"name:${name} age:${age}")
}
}
class Student(val name:String,val age:Int)
object Student{
def unapply(arg: Student): Option[(String, Int)] = {
if(arg==null)
None
else
Some((arg.name,arg.age))
}
}
def m1(sex:SEX) = {
println(".......")
}
}
3.8 赋值匹配
object $08_MatchParam {
def main(args: Array[String]): Unit = {
val tuple: (String, String, String) = m1(2,3)
tuple match {
case (x,y,z) => println("..")
}
//tuple._1,取第一个元素
//简化版
val (t1,t2,t3) = m1(2,3)
println(t1)//**
println(t2)//+++
println(t3)//2+3=5
//匹配第三个元素
val List(_,_,a,_*) = List(1,2,3,4,5)
println(a)
//打印结果 3
val Array(x,y,z) = Array(1,2,3)
println(x,y,z)
//打印结果(1,2,3)
val map =Map[String,Int] ( ("aa",1),("bb",2) )
for( i<- map )
println(i) //(aa,1) (bb,2)
//简化版
for( (k,v)<- map)
println(k,v) //(aa,1)(bb,2)
}
def m1(x:Int,y:Int) = {
println(s"${x} ${y}")
("*"*x,"+"*y,s"${x}+${y}=${x+y}")
}
}
3.9 偏函数
不使用match的模式匹配
object $09_MatchPartialFunction {
/**
* 偏函数:[不使用match的模式匹配]
* val func:PartialFunction[IN,OUT] = {
* case .. => ..
* }
*/
def main(args: Array[String]): Unit = {
val func:PartialFunction[Any,Int] = {
case x:String =>
println("string")
10
case y:Int =>
println("int")
20
case _ =>
println("other")
30
}
val i: Int = func(100)
println(i) //20
val school = List(
("北京小学",("小学一班",("1001","zhangsan",20))),
("北京小学",("小学一班",("1002","lisi",22))),
("北京小学",("小学一班",("1003","wangwu",23)))
)
//偏函数的应用场景
val func1:PartialFunction[(String,(String,(String,String,Int))),String] = {
case (schoolName,(className,(sid,sname,age))) => sname
}
println(school.map(func1))
println(school.map({
case (schoolName,(className,(sid,sname,age))) => sname
}))
}
}