Scala入门四——模式匹配

1. 值匹配

def m1():Unit={
    val arr = Array(1,2,3,4,5)
    val rand = Random.nextInt(arr.length)
    println(rand)
    val m = arr(rand) match {
      case 1 => "one"
      case 2 => "two"
      case 3 => "three"
      case 4 => "four"
      case 5 => "five"
      case _ => "other"
    }
    println(m)
  }

2. 类型匹配

  def m2():Unit={
    val arr = Array("scala",2,3.0,Demo)
    val rand = Random.nextInt(arr.length)
    println(rand)
    val m = arr(rand) match {
      case x:Int => println(s"Int $x")
      case y:Double => println(s"Double $y")
      case z:String => println(s"String $z")
      case _ => println("other")
    }
  }

3. 数组匹配

  def m3():Unit={
    val arr = Array(0,2,3,4)
    arr match {
      case Array(0,x,y) => println(s"x:$x, y: $y")
      case Array(1,2,3) => println("Array(1,2,3)")
      case Array(1,_*) => println("Array(1,_*)")
      case _ => println("other")
    }
  }

4. 集合匹配

  def m4():Unit={
    val ls = List(0,1,2,3)
    ls match {
      case 0 :: Nil => println("only 0")
      case x :: y :: Nil => println(s"x:$x, y: $y")
      case 0 :: a => println(s"0....$a")
      case _ => println("other")
    }
  }

5. tuple匹配

  def m5():Unit={
    val tup = (0,3,4)
    tup match {
      case (1,x,y) => println(s"x:$x, y: $y")
      case (0,z,5)  => println(s"z:$z")
      case _ => println("other")
    }
  }

6. 模式匹配,重点掌握

case class SubmitTask(id:Int,name:String)
case class HeartBeat(time:Long)
case object CheckTimeOutTask

/**
 * 样例类的模式匹配
 *  样例类:
 *      例如:case class SubmitTask
 *      多例,需要声明参数
 *  样例对象:
 *      例如:case object CheckTimeOutTask
 *      单例,不需要传递参数,加参数编译报错
 */

import scala.util.Random
object Demo2 extends App{
  val arr = Array(CheckTimeOutTask,HeartBeat(10000),SubmitTask(1,"task-00001"))

  arr(Random.nextInt(arr.length)) match {
    case SubmitTask(id:Int,name:String) => println(s"$id,$name")
    case HeartBeat(time:Long) => println(s"$time")
    case CheckTimeOutTask => println("CheckTimeOutTask")
  }
}

7. Option类型样例类 重点

/**
 * Option类型样例类:表示可能存在或可能不存在的值
 * Some包装了某个值
 * None表示没有值
 */
object OptionDemo {

  def main(args: Array[String]): Unit = {
    val map = Map("a"->1,"b"->2)
    val v = map.getOrElse("c", 0)
    println(v)

    /**
     * 说明:查看源码def get(key: K): Option[V],得知map.get("c")的返回值为 : Option 
     * sealed abstract class Option[+A]: Option为抽象类
     * 
     * Option有两个子类:
     * 1. final case class Some[+A](@deprecatedName('x, "2.12.0") value: A) extends Option[A]
     *      Some类为样例类,泛型为+A
     * 2. case object None extends Option[Nothing]
     *      None为样例对象,只有一份,泛型为Nothing
     * 
     * 查看getOrElse源码:发现其实现就是采用的模式匹配
     *   def getOrElse[V1 >: V](key: K, default: => V1): V1 = get(key) match {
     *          case Some(v) => v
     *          case None => default
     *   }
     * 
     * 
     */
    val v2 = map.get("c") match {
      case Some(value) => value
      case None => 0
    }
    println(v2)
  }
}

8. 偏函数

/**
 * 偏函数:被包在花括号内没有match的一组case语句是一个偏函数
 * 它是PartialFunction[A.B]的一个实例
 * 其中A代表参数类型,B代表返回值类型,常用作输入模式匹配
 */
object PartialFunctionDemo {

  def main(args: Array[String]): Unit = {
    println(func1("one"))

    println(func2("two"))
  }

  def func1 : PartialFunction[String,Int] = {
    case "one" => {
      println("one case")
      1
    }
    case "two" => 2
    case _ => -1
  }

  def func2(num:String):Int  = num match {
    case "one" => 1
    case "two" => 2
    case _ => -1
  }
}

猜你喜欢

转载自blog.csdn.net/guo20082200/article/details/82721547