1. 程式人生 > >雲星資料---Scala實戰系列(精品版)】:Scala入門教程036-Scala實戰原始碼-Scala match語句01

雲星資料---Scala實戰系列(精品版)】:Scala入門教程036-Scala實戰原始碼-Scala match語句01

Scala match語句

  • scala中的match語句用來在一個列表中選擇某一個分支來執行分支的語句塊,類似於其他語言中的swtich..case語句
package scala_learn.demo09_Match

/**
 * Created by liguohua on 2017/3/1.
 */
class O1_MatchDemo {

}

object O1_MatchDemo {
  def main(args: Array[String]) {
    test3()
  }

  //一個小用法
  def test4(x: Int): String = x match {
    case
1 => "one" case 2 => "two" case _ => "many" } def test3(): Unit = { val v1 = 5 //模式匹配中可以直接進行方法呼叫 var rs = v1 match { case 1 => "number one" case 2 => "number two" case 3 => "number three" //可以直接使用語句塊 case _ => { println("please reinput "
) //最後一句作為塊的返回值 "error number" } } println(rs) } def test2(): Unit = { val v1 = 5 //模式匹配中可以直接進行方法呼叫 var rs = v1 match { case 1 => println("number one") case 2 => println("number one") case 3 => println("number three") case _ => println("error number"
) } println(rs) } def test1(): Unit = { val v1 = 5 //模式匹配有返回值,不需要break,匹配後直接返回(有返回值) var rs = v1 match { case 1 => "number one" case 2 => "number two" case 3 => "number three" //模式匹配中可以直接使用語句塊 case _ => "error number" } println(rs) } }