1. 程式人生 > >雲星資料---Scala實戰系列(精品版)】:Scala入門教程048-Scala實戰原始碼-Scala Match操作

雲星資料---Scala實戰系列(精品版)】:Scala入門教程048-Scala實戰原始碼-Scala Match操作

Scala Match操作

package  scala_learn.demo11_Collection

/**
 * Created by liguohua on 2017/7/31.
 */
object O8_Match {

  def main (args: Array[String]) {
    //1.基本型別的match
        matchType(10)
    matchType("ketty")
    matchType(Map("zhangsan"->18,"lisi"->25))
    //2.陣列型別的match
    matchArray(Array
(20)) matchArray(Array(34)) matchArray(Array("zhang","li")) matchArray(Array(2,122,122,122)) //3.List型別的match matchList(List(20)) matchList(List(25)) matchList(List("zhang","li")) matchList(List(222,123,123,123)) //4.Tuple型別的match matchTuple(("zhangsan",18,"山東")) matchTuple(("li"
,20,"山東")) } def matchType(i:Any): Unit ={ i match { case p:Int=>println(p+" is Int") case p:String=>{println(p+" is string")} case m:Map[String,_]=>{m.foreach(println)} case _=>println("i don't konw!") } } def matchArray(arr:Array[Any]) = arr match { case
Array(20)=>println("陣列中有且只有一個元素20") case Array(x)=>println("陣列中有且只有一個元素: x="+arr(0)) case Array(x,y)=>println("陣列中有且只有兩個元素:x="+arr(0)+" , y="+arr(1)) case Array(29,_*)=>println("陣列中第一個元素是29,其他元素個數不限") case _=>println("Array其他情況") } def matchList(l:List[Any]) = l match { case List(20)=>println("List中有且只有一個元素20") case 25::nil=>println("List中有且只有一個元素25") case x::nil=>println("List中有且只有一個元素:x="+x) case x::y::nil=>println("陣列中有且只有兩個元素:x="+x+" , y="+y) case 222::tail=>println("第一個元素是222,後面的元素不限") case _=>println("List其他情況") } def matchTuple(t:Any) = t match { case ( "zhangsan" , _,_ ) => println("元組的第一個元素是:zhangsan") case ( _,20,_ ) => println("元組的第二個元素是:20") case _=>println("Tuple其他情況") } }