1

模式匹配

常量模式

    def constansMatch(x: Any): Any = x match {

      case 5 => "five"
      case true => "true"
      case "hello" => "hello"
      case Nil => "empty List"
      case _ => "something else"
    }

    println(constansMatch(5))
    println(constansMatch(true))
    println(constansMatch("hello"))
    println(constansMatch(List()))
    println(constansMatch(List(1, 2, 3)))

变量模式

def variableMatch(x:Any): Unit = x match {
      case 0 => println("zero")
      case something => println(s"not zero $something")
    }

    variableMatch(0)
    variableMatch("hello")
    variableMatch(1)

序列模式

def seqMatch(list: Any): Unit = list match {

      case List(0,_,_) => println("found 3 list")
      case List(0,_*) => println("zero start, very much value list")
      case _ => throw new Error("error")
    }

    seqMatch(List(0,1,2))
    seqMatch(List(0,5,6,7,8))
    seqMatch(List(0,1))
    seqMatch(0)

元组模式

def tupleMatch(tuple: Any): Unit = tuple match {
      case (a, b, c) => println(s"match $a,$b,$c")
      case _ => throw new Error
    }

    tupleMatch((1, 2, 3))
    tupleMatch((1, 2))

带类型模式

def typeMatch(t:Any): Unit =t match {
      case s:String => println(s)
      case i:Int => println(i)
      case m:Map[_,_] => println(m)
      case _ => throw new Error
    }

    typeMatch("ljk")
    typeMatch(18)
    typeMatch(Map("ljk" -> 18))
    typeMatch("ljk",18)

变量守卫

def guardMatch(x:Any): Unit =x match {
      case n:Int if n>0 => println(n)
      case s:String if s(0)=='a' => println(s)
      case _ => throw new Error
    }
    guardMatch(1)
    guardMatch("aaaa")
    guardMatch(0)

密封类

担心漏掉某些可能case的模式匹配
编译警告:missing combination Int2

sealed abstract class Expr

    case class Var(name: String) extends Expr

    case class Number(num: Double) extends Expr

    case class Int2(i: Int) extends Expr

    def classMatch(e: Expr): Unit = e match {
      case Var(_) => println(s"String $e")
      case Number(_) => println(s"Double $e")
    }

    classMatch(Var("ljk"))
    classMatch(Number(888D))

Option类型

    val map = Map("ljk"->18)

    def optionMatch(op:Any): Unit =op match {
      case Some(_) => println(op)
      case None => println("nothing")
    }

    optionMatch(map.get("ljk"))
    optionMatch(map.get("lljk"))

到处都是模式

    val myTuple = (123, "abc")
    val (num, str) = myTuple
    println(s"num $num, str $str")

    val withDefault: Option[Int] => Int = {
      case Some(x) => x
      case None => 0
    }

    println(withDefault(Some(10)))
    println(withDefault(None))

小鸡
214 声望24 粉丝

1.01的365次方=37.8


引用和评论

0 条评论