Scala模式匹配

模式匹配

基本数据类型模式匹配

  val names = List("小红", "小明", "小鬼")

  val name = names(Random.nextInt(names.length))

  name match {
    case "小红" => println("she is a beautiful girl")
    case "小明" => println("he is a cool boy")
    case _ => println("can not find this is name")
  }

加条件进行匹配

case _ if name == "小鬼" => println("litter box")

Array模式匹配

sizeMatch(Array("small"))
  sizeMatch(Array("small", "medium"))
  sizeMatch(Array("small", "medium", "high", "highest"))

  def sizeMatch (arr:Array[String]) = {
    arr match {
      case Array(x, y) => println(x, y)
      case Array(x, y, _*) => println(x, y, "any more")
      case _ => println("nothing...")
    }
  }

匹配到一个就返回跟Java不一样

List模式匹配

类似Array

  listMatch(List("small"))
  listMatch(List("small", "medium"))
  listMatch(List("medium", "high", "highest"))
  def listMatch (arr:List[String]) = {
    arr match {
      case "small"::Nil => println(arr)
      case "medium"::tail => println(tail)
      case _ => println("any")
    }
  }

类型模式匹配

  typeMatch("hello world")
  typeMatch(Map(List("1") -> "22"))
  typeMatch(Map("1" -> 222))

  def typeMatch (varType:Any) = {
    varType match {
      case x:String => println(varType)
      case y:Map[String, Int] => println("this is map")
      case _ => println("nothing")
    }
  }

这里map不匹配类型 通吃

Scala异常处理

  try {
    val number:Number = 1 / 0
    println(number)
  }catch {
    case e:ArithmeticException => println(e)
    case e:Exception => println(e.getMessage)
  }

class模式匹配

  class Person
  case class Woman(sex:String) extends Person
  case class Man(sex:String) extends Person

  classMatch(Woman("女"))
  classMatch(Man("男"))

  def classMatch (person: Person) = {
    person match {
      case Woman(sex:String) => println("this is woman class")
      case Man(sex:String) => println("this is man class")
      case _ => println("nothing")
    }
  }

Some&None模式匹配

你可能感兴趣的:(scala)