scala中的case語法與java中的switch語法相似,但比switch更強大:java
例子一正則匹配:微信
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*
例子二等值匹配:spa
val v1=1 val r=v1 match { case 1=> "1" case 2=> "1" case 3=> "2" case _=> "default" } println(r)// 1
例子三範圍匹配:scala
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
變形語法:code
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)
例子四多值匹配:圖片
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 類型
例子五正則多值匹配:get
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"))
有什麼問題能夠掃碼關注微信公衆號:我是攻城師(woshigcs),在後臺留言諮詢。 技術債不能欠,健康債更不能欠, 求道之路,與君同行。string