Scala 模式匹配

2021-10-25 07:28:54 字數 998 閱讀 8088

模式匹配是乙個十分強大的機制,可以應用在很多場合: switch語句、型別查詢,以及「析構」(獲取複雜表示式中的不同部分)。樣例類針對模式匹配進行了

優化。

def match0(x:int):string = else if(x==2)else

}

def match1(x:int):string=x match
與 switch語句不同, scala模式匹配並不會有「意外掉入下乙個分支」的問題。(在c和其他類c語言中,你必須在每個分支的末尾顯式地使用 break語句來退出

witch,否則將掉入下乙個分支。這很煩人,也容易出錯。)

同時,你可以用 | 來分隔多個選項,而且,你可以在 match表示式中使用任何型別,而不僅僅是數字。

def studentscore(name:string,score:string): unit = score match
def match6(e:exception):unit = e match
def match7(arr:array[string]):unit = 

}

case class teacher2(name:string,age:int) extends person

case class student2(name:string,age:int) extends person

case class worker2(name:string,age:int) extends person

case class msr(name:string,age:int) extends person

def match8(p:person):unit =

}

def match9(name:string):unit = 

}

Scala模式匹配

1.常量匹配 def constantmatch x int string x match def constantmathtest 輸出結果 one many2.列表匹配 def sequencematch x list int string x match def sequencemathtes...

scala模式匹配

這是scala中最有用的部分之一。匹配值val times 1 times match 使用守衛進行匹配 times match 注意我們是怎樣將值賦給變數 i 的。在最後一行指令中的 是乙個萬用字元 它保證了我們可以處理所有的情況。否則當傳進乙個不能被匹配的數字的時候,你將獲得乙個執行時錯誤。我們...

scala模式匹配

這是scala中最有用的部分之一。匹配值val times 1 times match 使用守衛進行匹配 times match 注意我們是怎樣將值賦給變數 i 的。在最後一行指令中的 是乙個萬用字元 它保證了我們可以處理所有的情況。否則當傳進乙個不能被匹配的數字的時候,你將獲得乙個執行時錯誤。我們...