scala之matchcase⽤法详解scala中的case语法与java中的switch语法类似,但⽐switch更强⼤:
例⼦⼀正则匹配:
val Pattern="(s.*)".r
val v1="spark";
val r=v1 match  {
case Pattern(v1)=> "begin s*"
case "1"=> "1"
case "2"=> "2"
case _=> "default"
}
println(r) // begin s*
例⼦⼆等值匹配:
val v1=1
val r=v1 match  {
case 1=> "1"
case 2=> "1"
case 3=> "2"
case _=> "default"
}
println(r)// 1
例⼦三范围匹配:
val v1=3
val r=v1 match  {
case v1 if 1 until 5 contains v1=> "1-5"
case v1 if 5 until 10 contains v1=> "5-10"
case _=> "not found"
}
println(r)//1-5
变形语法:
val v1=3
val r=v1 match  {
case v1 if (v1>0 && v1<=5) => "1-5"
case v1 if (v1>5 && v1<=10)=> "5-10"
case _=> "not found"
}
println(r)
例⼦四多值匹配:
java switch case string
def glob(x:Any):Any= x match {
case 1 | “1” | “one” => "one "
case “two”=> 2
case s:String => “String”
case y:Int=>"Int 类型 "
case _ => “其他”
}
println(glob(4))//Int 类型
例⼦五正则多值匹配:
val Pattern1="(quest_.)".r
val Pattern2="(kp_max_.)".r
val Pattern3="(ukq_.)".r
/**
* 根据提供的key返回value数据,屏蔽底层差异
* @param key
*/
def get(key:String):Any= key match {
case Pattern1() | Pattern2() => r.get(key) //返回string
case Pattern3(_) => r.lrange(key,0,29).get //返回list
case _ => “”
}
println(get(“kp_max_1000168”))
println(get(“quest_494bdc1bd1c34cfa8064d8d38382659f”)) println(get(“ukq_1001_10034”))
println(get(“xfd”))

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。