scala类型匹配注意事项

1)Map[String,Int]和Map[Int,String]是两种不同的类型,其他的类推,List[Int],List[String]其他类推
2)在进行类型匹配时,编译器会预先检测是否有可能的匹配,如果没有则报错

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 = 0 的key -value,其他过滤掉
    println("---------------(k,0)<- map---------------")
    for ((k,0)<- map) {
    
    
      println(k + " -->" + 0)
    }

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

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

    val arrs = Array(Array(0),Array(1,0),Array(0,1,0),
        Array(1,1,0),Array(1,1,0,1))

    for (arr <- arrs ) {
    
    
      val result = arr match {
    
    
        case Array(0) => "0"
        case Array(x,y) => x + "="  + y
        case Array(0,_*) => "以0开头和数组"
        case _ => "什么集合都不是"
      }
      // result = 0
      // result = 1 =0
      // result = 以0开头和数组
      // result = "什么集合都不是"
      // result = "什么集合都不是"
      println("result =" + result)
    }
  }
}

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

    val arrs2 = Array(Array(0),Array(1,0),Array(0,1,0),
        Array(1,1,0),Array(1,1,0,1))

    for (arr <- arrs2 ) {
    
    
      val result = arr match {
    
    
        case Array(0) => "0"
        case Array(x,y) => Array(y,x)
        case Array(0,_*) => "以0开头和数组"
        case _ => "什么集合都不是"
      }
      // result = 0
      // result = 1 =0
      // result = 以0开头和数组
      // result = "什么集合都不是"
      // result = "什么集合都不是"
      println("result =" + result)
    }

    // 给你一个数组集合,如果该数组是 Array(10,20),请使用模式匹配,返回Array(20,10)



  }
}

object CaseClassDemo01 {
    
    

  def main(args: Array[String]): Unit = {
    
    
     println("hello~~~")
  }
}

abstract class Amount
case class Dollar(value:Double) extends Amount // 样例类
case calss Currency(value:Double,unit:String) extends Amount // 样例类
case object NoAmount extends Amount //样例类

猜你喜欢

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