Scala模式匹配

object MatchDemo {
  /**
    * 定义偏函数用PartialFunction来表示
    * PartialFunction[T1,T2],T1表示传入参数的数据类型,T2表示返回值的数据类型
    * 偏函数体中的case只会执行一个,如果匹配到了就不会继续往下匹配
    */
  val func: PartialFunction[String, Int] = {
    case "a" => 1
    case "b" => 2
    case _ => -1
  }

  /**
    * 匹配字符串
    */
  def matchString(str: String) = {
    str match {
      case "a" => 1
      case "b" => 2
      case _ => -1
    }
  }

  /**
    * 匹配类型
    */
  def matchType(x: Any) = {
    x match {
      case x: String => println(x.getClass + " " + x)
      case x: Int if x > 5 => println(x)
      case _ => println("unknown")
    }
  }

  /**
    * 匹配数组
    */
  def matchArray(array: Array[Int]) = {
    array match {
      case Array(1, x, y) => println("匹配以1开头,有三个元素的数组")
      case Array(0) => println("匹配只有0这个元素的数组")
      case Array(0, _*) => println("匹配以0开头,任意多个元素的数组")
      case _ => println("unknown")
    }
  }

  /**
    * 匹配序列List
    * Nil是一个空的List,定义为List[Nothing]
    */
  def matchList(list: List[Int]) = {
    list match {
      case 5 :: Nil => println("匹配只有5这个元素的序列")
      case x :: y :: Nil => println("匹配只有两个元素的序列")
      case x :: tail => println("匹配有任意多个元素的序列")
      case _ => println("unknown")
    }
  }

  /**
    * 匹配元组
    */
  def matchTuple(tuple:Any) = {
    tuple match {
      case (x, y, 6) => println("匹配只有三个元素并且以6结尾的元组")
      case (1, x, y) => println("匹配以1开头有三个元素的元组")
      case _ => println("unknown")
    }
  }

  def main(args: Array[String]): Unit = {
    val test = func("a")
    println(test)
    println(matchString("b"))
    matchType("你好")
    matchType(3)
    matchType(6)
    matchType(1.5)
    println("============================")
    matchArray(Array(1, 2, 3))
    matchArray(Array(0))
    matchArray(Array(0, 1, 2, 3))
    matchArray(Array(1, 2))
    println("=========================")
    matchList(List(5, 6, 7))
    println("=========================")
    matchTuple((1,2,6))
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值