目录
匹配常量、类型、数组、列表、元组、匹配元组扩展
package chapter08
object Test01_PatternMatchBase {
def main(args: Array[String]): Unit = {
//1.基本定义语法
val x:Int=2
val y:String=x match {
case 1=>"one"
case 2=>"two"
case 3=>"three"
case _=>"other"
}
println(y)
//2.示例:用模式匹配实现简单二元运算
val a=26
val b=13
def matchDualOp(op:Char):Any=op match {
case '+'=>a+b
case '-'=>a-b
case '*'=>a*b
case '/'=>a/b
case '%'=>a%b
case _=> "非法运算符" //Any
}
println(matchDualOp('+'))
println(matchDualOp('-'))
println(matchDualOp('/'))
println("---------------------------")
//3.模式守卫
//求一个整数的绝对值
def abs(num:Int):Int={
num match {
case i if i>=0 =>i
case i if i<0 => -i
}
}
println(abs(-2))
}
}
package chapter08
//模式匹配类型
object Test02_MatchTypes {
def main(args: Array[String]): Unit = {
//1.匹配常量 const常量
def describeConst(x:Any):String=x match {
case 1=>"Int one"
case "hello"=>"String hello"
case true =>"Boolean true"
case "+"=>"Char +"
case _ =>"" //默认语句
}
println(describeConst("hello"))
println(describeConst("+"))
println(describeConst(0.3))
println("--------------------------------")
//2.匹配类型
def describeType(x:Any):String=x match {
case i:Int=>"Int "+i
case s:String=>"String "+s
case list:List[String]=>"List "+list
case array:Array[Int]=>"Array[Int] "+array.mkString(",")
case a=>"Something else: " +a
}
println(describeType(35))
println(describeType("hello"))
println(describeType(List("hi","hello")))
println(describeType(List(2,23))) //直接匹配上 因为存在泛型擦除
println(describeType(Array("hi","hello"))) //Array没有泛型擦除
println(describeType(Array(2,23)))
//3.匹配数组
for (arr <- List(
Array(0),
Array(1,0),
Array(0,1,0),
Array(1,1,0),
Array(2,3,7,15),
Array("hello",1,30)
)) {
val result =arr match {
case Array(0) =>"0"
case Array(1,0) =>"Array(1,0)"
case Array(x,y)=>"Array: "+ x +","+ y //匹配两元素组
case Array(0,_*)=>"以0开头的数组" //(0,1,0) 满足一个就结束
case Array(x,1,z)=>"中间为1的三元素数组"
case _=>"something else"
}
println(result)
}
println("------------------------------")
//4.匹配列表
//方式一
for(list <-List(
List(0),
List(1,0),
List(0,0,0),
List(1,1,0),
List(88)
)){
val result =list match{
case List(0)=>"0"
case List(x,y)=>"List(x,y): "+ x + "," +y
case List(0,_*) =>"List(0,....)"
case List(a) =>"List(a): " +a
case _=>"something else"
}
println(result)
}
//方式二
val list1=List(1,2,5,7,24)
val list2=List(24)
list1 match{
case first :: second :: rest =>println(s"first: $first,second: $second,rest:$rest")
case _=>println("something else")
}
list2 match{
case first :: second :: rest =>println(s"first: $first,second: $second,rest:$rest")
case _=>println("something else")
}
println("-------------------------------------------------")
//5.匹配元组
for(tuple <- List(
(0,1),
(0,0),
(0,1,0),
(0,1,1),
(1,23,56),
("hello",true,0.5)
)){
val result=tuple match{
case (a,b)=>" "+ a + "," + b
case (0,_)=>"(0,_)"
case (a,1,_)=>"(a,1,_) " + a
case (x,y,z)=>"(x,y,z)" + x + " " +y + " " +z
case _=> "something else"
}
println(result)
}
}
}
package chapter08
//匹配元组扩展
object Test03_MatchTupleExtend {
def main(args: Array[String]): Unit = {
//1.在变量声明时匹配
val (x,y)=(10,"hello")
println(s"x:$x,y:$y")
val List(first,second,_*)=List(23,15,9,78)
println(s"first:$first,second$second")
val fir :: sec :: rest =List(23,15,9,78) //双冒号
println(s"first:$first,second:$second,rest$rest")
println("-------------------------------------")
//2.for推导式中进行模式匹配
val list:List[(String,Int)]=List(("a",12),("b",35),("c",27),("a",13))
//2,1 原本的遍历方式
for (elem <- list){
println(elem._1+ " "+elem._2)
}
//2.2 将List的元素直接定义为元组,对变量赋值
for((word,count) <- list){
println(word + ":" + count)
}
//2.3 可以不考虑某个位置的变量,只遍历key或者value
for ((word, _) <- list)
println(word)
//2.4可以指定某个位置的值必须是多少
for (("a",count) <-list){
println(count)
}
}
}
匹配对象及样例类
package chapter08
//匹配对象及样例 用模式匹配 匹配对象
object Test04_MatchObject {
def main(args: Array[String]): Unit = {
val student=new Student("bob",18)
//针对对象实例的内容进行匹配
val result=student match{
case Student("alice",18)=>"Alice,18" //对象放在这 跟另外一个对象匹配
case _=>"something else"
}
println(result)
}
}
//定义类
class Student(val name:String,val age:Int)
//定义伴生对象
object Student{
def apply(name:String,age:Int):Student=new Student(name,age)
//必须实现一个unapply方法,用来对对象属性进行拆解
def unapply(student: Student): Option[(String, Int)] ={
if (student == null){
None
}else{
Some((student.name,student.age))
}
}
}
package chapter08
//样例类匹配对象 对象实例的模式匹配的话 使用样例类最为简单最为快捷
object Test05_MatchCaseClass {
def main(args: Array[String]): Unit = {
val student= Student1("alice",19)
//针对对象实例的内容进行匹配
val result=student match{
case Student1("alice",18)=>"Alice,18" //对象放在这 跟另外一个对象匹配
case _=>"something else"
}
println(result)
}
}
//定义样例类
case class Student1( name:String, age:Int) //样例类默认是当前的属性 不需要val
偏函数
package chapter08
//偏函数
object Test06_PartialFunction {
def main(args: Array[String]): Unit = {
val list:List[(String,Int)]=List(("a",12),("b",35),("c",27),("a",13))
//1.map转换,实现key不变,value2倍
val newList=list.map(tuple =>(tuple._1,tuple._2*2))
//2.用模式匹配对元组元素赋值,实现功能
val newList2=list.map(
tuple=>{
tuple match {
case (word,count)=>(word,count*2)
}
}
)
//3.省略lambda表达式的写法,进行简化
val newList3=list.map{
case(word,count)=>(word,count*2) //偏函数
}
println(newList)
println(newList2)
println(newList3)
//偏函数的应用,求绝对值
//对输入数据分为不同的情形:正、负、0
val positiveAbs:PartialFunction[Int,Int]={
case x if x>0 =>x
}
val negativeAbs:PartialFunction[Int,Int]={
case x if x<0 => -x
}
val zeroAbs:PartialFunction[Int,Int]={
case 0 =>0
}
def abs(x:Int):Int=(positiveAbs orElse negativeAbs orElse zeroAbs)(x)
println(abs(-67))
println(abs(35))
println(abs(0))
}
}
版权声明:本文为liuyongsheng666原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。