14.2 scala默认首字母大写的字符串为常量,首字母小写的字符串为变量,如果希望在模式匹配中用首字母小写的常量需要用反引号 ` 进行标注
scala> val ch = 3.14
scala> val mypi = 3.14
scala> val res = ch match {
| case `mypi` => true
| case _ => false
| }
res: Boolean = true
14.3类型模式:
scala> def GetInt(x:Any):Int = {
x match {
case i:Int => i
case s:String => Integer.parseInt(s.trim)
case z:scala.math.BigInt => Int.MaxValue
case c:Char => c.toInt
case _ => 0
}
}
GetInt: (x: Any)Int
14.4守卫:
scala> val ch = 3.14
scala> ch match {
| case x if(x>3&&x<4) => true
| case _ => false
| }
res9: Boolean = true
14.5匹配数组,列表和元组
定义模式匹配函数matchArr:
scala> def matchArr(x:Array[Int]):String =
| x match {
| case Array(0) => "Only 0" //仅含一个元素0的数字
| case Array(x,y) => x+" "+y //仅含有两个元素的数组
| case Array(0,_*) => "Strat from 0" //0开始的数组
| case _=> "Something else"
| }
// matchArr: (x: Array[Int])String
scala> matchArr(Array(0))
// res21: String = Only 0
scala> matchArr(Array(0 to 20).flatten)
// res23: String = Strat from 0
14.6提取器:
scala> val pattern = "([0-9]+) ([a-z]+)".r
pattern: scala.util.matching.Regex = ([0-9]+) ([a-z]+)
scala> "99 bottles" match {
| case pattern(num,item) => println("num => "+num +" item => " + item)
| case _ =>
| }
num => 99 item => bottles
14.7变量声明中的模式
scala> val (x,y) = BigInt(10) /% 3
x: scala.math.BigInt = 3
y: scala.math.BigInt = 1
/% 方法返回包含商和余数的对偶,而这两个值分别被变量x和y捕获
同理也可以用于任何有变量的模式
scala> val Array(first,second,_*) = arr.flatten
first: Int = 0
second: Int = 1
scala> val ch = 3.14
scala> val mypi = 3.14
scala> val res = ch match {
| case `mypi` => true
| case _ => false
| }
res: Boolean = true
14.3类型模式:
scala> def GetInt(x:Any):Int = {
x match {
case i:Int => i
case s:String => Integer.parseInt(s.trim)
case z:scala.math.BigInt => Int.MaxValue
case c:Char => c.toInt
case _ => 0
}
}
GetInt: (x: Any)Int
14.4守卫:
scala> val ch = 3.14
scala> ch match {
| case x if(x>3&&x<4) => true
| case _ => false
| }
res9: Boolean = true
14.5匹配数组,列表和元组
定义模式匹配函数matchArr:
scala> def matchArr(x:Array[Int]):String =
| x match {
| case Array(0) => "Only 0" //仅含一个元素0的数字
| case Array(x,y) => x+" "+y //仅含有两个元素的数组
| case Array(0,_*) => "Strat from 0" //0开始的数组
| case _=> "Something else"
| }
// matchArr: (x: Array[Int])String
scala> matchArr(Array(0))
// res21: String = Only 0
scala> matchArr(Array(0 to 20).flatten)
// res23: String = Strat from 0
14.6提取器:
scala> val pattern = "([0-9]+) ([a-z]+)".r
pattern: scala.util.matching.Regex = ([0-9]+) ([a-z]+)
scala> "99 bottles" match {
| case pattern(num,item) => println("num => "+num +" item => " + item)
| case _ =>
| }
num => 99 item => bottles
14.7变量声明中的模式
scala> val (x,y) = BigInt(10) /% 3
x: scala.math.BigInt = 3
y: scala.math.BigInt = 1
/% 方法返回包含商和余数的对偶,而这两个值分别被变量x和y捕获
同理也可以用于任何有变量的模式
scala> val Array(first,second,_*) = arr.flatten
first: Int = 0
second: Int = 1