网站建设的风格设置,小程序设计案例,怎么设置网站的logo,网上做效果图一、匹配常量
在scala中#xff0c;模式匹配可以匹配所有的字面量#xff0c;包括字符串#xff0c;字符#xff0c;数字#xff0c;布尔值等等 def describeConst(x:Any):String x match {case str 匹配字符串case 匹配字符模式匹配可以匹配所有的字面量包括字符串字符数字布尔值等等 def describeConst(x:Any):String x match {case str 匹配字符串case 匹配字符case 1 匹配整数case true 匹配布尔值case a s匹配$a}println(describeConst(str))println(describeConst())println(describeConst(1))println(describeConst(true))println(describeConst(-)) 二、匹配类型 def describeType(x:Any):String x match {case x:String 匹配字符串case x:Char 匹配字符case x:Int 匹配整数case x:Boolean 匹配布尔值case list:List[String] List listcase array:Array[Int] Array array.mkString(\t)case a s匹配$a}println(describeType(str))println(describeType())println(describeType(1))println(describeType(true))println(describeType(List(a,b,c)))// 泛型擦除println(describeType(List(1,2,3,4,5)))println(describeType(Array(1,2,3,4,5)))// array不存在泛型擦除println(describeType(Array(1,2)))三、匹配集合类型
代码
for (arr - List(Array(0),Array(1,0),Array(0,1,0),Array(1,1,0),Array(2,3,7,15),Array(hello,a,30))){val result arr match{case Array(0) 0case Array(1,0) Array(1,0)case Array(x,y) Array: x , ycase Array(0,_*) 以0开头的数组case Array(x,1,z) 中间为1的三元素数组case _ Something else}println(result)}结果 for(list - List(List(0),List(1,0),List(0,0,0),List(1,1,0),List(88),List(hello))){val result list match {case List(0) 0case List(x,y) List(x,y): x , ycase List(0,_*) List(0...case List(a) List(a) acase _ something else}println(result)}结果 代码 val list1 List(1,2,5,7,24)val list List(24)list match {case first :: second :: rest println(sfirst$first, second$second , rest: $rest)case _ println(something else)}list1 match {case first :: second :: rest println(sfirst$first, second$second , rest: $rest)case _ println(something else)}
结果 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 , bcase (0,_) (0, _)case (a,1,_) (a,1,_) acase _ something else}println(result)}
结果 在变量声明时匹配 val (x,y) (10,hello)println(sx$x,y$y)val List(first,second,_*) List(23,15,9,78)println(sfirst$first,second$second)val fir :: sec :: rest List(23,15,9,78)println(sfirst$fir,second$sec,rest$rest) for推导式中进行模式匹配
将List的元素直接定义为元组对变量赋值 val list List((a,12),(b,35),(c,27))for ((word,count) - list){println(word count)} 可以不考虑某个位置的变量只遍历key或者value val list List((a,12),(b,35),(c,27))for ((word,_) - list)println(word)可以指定某个位置的值必须是多少 val list List((a,12),(b,35),(c,27),(a,99))for((a,count) - list){println(count)}四、匹配对象及样例类 package scala
object User {def main(args: Array[String]): Unit {val student Student(alice,19)val result student match {case Student(alice,19) Alice, 19case _ Else}println(result)}case class Student(name:String,age:Int)}