Scala入门与进阶(五)- 模式匹配

作者: 9c0ddf06559c | 来源:发表于2018-07-29 17:09 被阅读7次

    6.模式匹配

    1.最基础的模式匹配

    Java: 对一个值进行条件判断,返回针对不同的条件进行不同的处理

    Scala:

    变量 match {
    case value1 =>代码1,
    case value2 =>代码2,
    ...
    case _ => 代码N
    }
    
    object MatchApp extends App {
    
    val names = Array("zhangsan","lisi","wangwu")
    val name = names(Random.nextInt(names.length))
    
    name match {
    case "zhangsan" => println("张三...")
    case "lisi" => println("李四...")
    case _ => println("真的不知道你们在说什么")
    }
    
    }
    

    2.加条件进行匹配

    3.Array模式匹配

    def greeting(array:Array[String])={
    array match{
    case Array("zhangsan") => println("Hi zhangsan")
    case Array(x,y) => println("Hi "+x+" , "+y)
    case Array("zhangsan",_*) => println("Hi zhangsan and other friends")
    case _ => println("Hi everybody")
    }
    }
    

    4.List模式匹配

    image.png

    5.类型匹配

    def matchType(obj:Any)={
    obj match {
    case Int => println("Int")
    case String => println("String")
    case m:Map[_,_] => m.foreach(println)
    case _ => println("other type")
    }
    }
    

    6.Scala异常处理

    image.png

    7.case class

    class Person
    case class CTO(name: String,floor:Int) extends Person
    case class Employee(name: String,floor:Int) extends Person
    case class Other(name:String) extends Person
    
    def caseclassMatch(person: Person)={
    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")
    }
    }
    

    相关文章

      网友评论

        本文标题:Scala入门与进阶(五)- 模式匹配

        本文链接:https://www.haomeiwen.com/subject/kgftvftx.html