变量声明的模式

基本介绍
match中的每一个case都可以单独提取出来,意思是一样的
应用案例

object MatchVarDemo {
    
    
  def main(args: Array[String]): Unit = {
    
    

    val (x,y,z) = (1,2,"hello")
    print("x=" + x )

    val(q,r) = BigInt(10) /% 3 // 说明 q = BigInt(10) /3r = BigInt(10)%3
    val arr = Array(1,7,2,9)


    val Array(first,second,_*) = arr //提出arr的前两个元素
    println(first,second)

  }
}

for表达式中的模式
基本介绍
for循环也可以进行模式匹配
object MatchForDemo {
    
    
  def main(args: Array[String]): Unit = {
    
    
    val map = Map("A"->1,"B"->0,"C"->3)
    for((k,v) <- map) {
    
    
      println(k + " ->" + v) // 出来三个key-value ("A"->1,"B"->0,"C"->3)
    }
    // 说明:只遍历出value = 的key-value,其他的过滤掉
    println("-----------------------------------------------------")
    for((k,0) <- map) {
    
    
      println(k + " -->" + 0)
    }

    // 说明,这个就是上面代码的另外写法,只是下面的用法更加灵活和强大
    println("-------------------(k,v) <- map if v == 0------------")
    for((k,v) <- map if v == 1) {
    
    
      println(k + "----->" + v)
    }
  }

}

猜你喜欢

转载自blog.csdn.net/qq_44104303/article/details/114789364
今日推荐