6. Scala模式匹配

China☆狼群 提交于 2019-12-05 23:00:16

模式匹配

Java中 case when:对一个值进行条件判断,返回针对不同的条件进行不同的处理
Scala语法:
变量 match{
case value1 => 代码一
case vlaue2 => 代码二
...
case _ => 代码N
}

package com.yy.scala

object MatchApp extends App {

  matchName("Tom", 60)
  matchName("Lucy", 60)

  matchArray(Array("Tom","Lily"))

  matchList(List("Tom","Lily","Lucy"))

  matchType(1)
  matchType(Map("age"->12))

  caseclassMath(CTO("David", "10"))
  caseclassMath(Employee("Kit", "14"))

  //基础类型匹配
  def matchName(name: String, age : Int): Unit ={
    name match {
      case  "Tom" => println("汤姆")
      case  "Jim" => println("吉姆")
      case  _ if age > 50  => println("old "+name)
      case  _ => println("young "+name)
    }
  }

  //数组匹配
  def matchArray(array:Array[String]) = {
    array match {
      case  Array("Tom") => println("Hello Tom")
      case  Array(x,y) => println("Hello "+x+","+y)
      case  Array("Tom",_*)  => println("Hello Tom and other friends")
      case  _ => println("Hello everybody")
    }
  }

  //List匹配
  def matchList(list:List[String]) = {
    list match {
      case  "Tom"::Nil => println("Hello Tom")
      case  x::y::Nil => println("Hello "+x+","+y)
      case  "Tom"::tail  => println("Hello Tom and other friends")
      case  _ => println("Hello everybody")
    }
  }

  //类型匹配
  def matchType(obj:Any) = {
    obj match {
      case i:Int => println("Int")
      case s:String => println("String")
      case m:Map[_,_] => m.foreach(println)
      case _ => println("other type")
    }
  }

  //case class模式匹配
  def caseclassMath(person: Person): Unit ={
    person match {
      case CTO(name,floor) => println("CTO name is "+name+", floor is" + floor)
      case Employee(name,floor) => println("Employee name is "+name+", floor is" + floor)
      case _ => println("other")
    }
  }

  class Person
  case class CTO(name:String, floor:String) extends Person
  case class Employee(name:String, floor:String) extends Person
  case class Other(name:String) extends Person
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!