Scala入门到放弃—05—模式匹配

发布时间:2024年01月17日

模式匹配

基本类型

Java : 对一个值进行条件判断例如switch

模式匹配类似于Javaswitch caseScala的模式匹配不仅可以匹配值还可以匹配类型、从上到下顺序匹配,如果匹配到则不再往下匹配、都匹配不上时,会匹配到case _ ,相当于defaultmatch 的最外面的{ }可以去掉看成一个语句。


def match_test(m:Any) = {
       m match {
         case 1 => println("num 1 ")
         case m:Int => println("Int")
         case _ => println("default")
       }
    }

package org.example
object MarchApp {
  def main(args: Array[String]): Unit = {
    def judeGrade(grade:String)={
      grade match{
        case "B" => println("Just so so")
        case "A" => println("good")
        case "S" => println("cool")
        case _=> println("No.1")
      }
    }
    judeGrade("S")
    judeGrade("A")
    judeGrade("SSS")
  }
}

```scala
> cool
good
No.1

Array匹配模式

    def greeting(array:Array[String]) = {
      array match {
        case Array("zs")=> println("hi,zs")
        case Array(x,y)=> println(x+"and"+y)
        case Array("zs",_*)=>println("zs and other")
        case _=>println("everyone")
      }
    }
    greeting(Array("zs"))
    greeting(Array("zs","ls"))

hi,zs
zsandls

_* : _表示多个,*是可变参数,

List集合的模式匹配

    def greeting1(list:List[String]) = {
      list match {
        case "zs"::Nil=> println("hi,zs")
        case x::y::Nil=> println(x+"and"+y)
        case "zs"::tail =>println("zs and other")
        case _=>println("everyone")
      }
    }
    greeting1(List("zs"))
    greeting1(List("zs","ls"))
  }

hi,zs
zs and ls

类型的匹配模式

    def matchType(obj: Any) = {
      obj match {
        case x: Int => println("hi,int")
        case y: String => println(y)
        case m: Map[_, _] => println("map")
        case _ => println("everyone")
      }
    }
    matchType(Map(1 -> "yes"))
    matchType(11)
    matchType("hello")
  }

异常处理


 try{
      val i=10/0
      println(i)
    }catch {
      case e:ArithmeticException=>println(e.getMessage)
      case e:Exception=>println(e.getMessage)
    }finally {
		// 释放资源,一定会执行
    }

/ by zero

case class的匹配

cass class 可以直接使用,不用new


def caseclassMatch(person: Person) : Unit = {
person match {
	case CTO(name, floor) => println("CTO name is: " + name + " )
	case Employee(name , floor) => println( "Employee name is: " + name + ")
	case_ =>println("hello")
	}

}


class Person
case class GT0(name:String,floor:String) extends Person
case class Employee(name:String, floor:String) extends Personcase class Other( name:String) extends Person
caseclassMatch(CTO("lisi","22"))
caseclassMatch(Employee( "zhangsan", "2"))caseclassMatch(0ther( "other" ))
文章来源:https://blog.csdn.net/jankin6/article/details/124943084
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。