Scala模式匹配

1.常量匹配

def constantMatch(x: Int): String = x match {
    case 1 => "one"
    case 2 => "two"
    case _ => "many"
  }
def constantMathTest()={
    println(constantMatch(1))
    println(constantMatch(5))
  }

输出结果

one
many

2.列表匹配

def sequenceMatch(x: List[Int]): String = x match {
    case List(5, _, _) => "匹配5元素开头的三元素列表"
    case List(1, _*) => "匹配以1开头任意数目的列表"
    case _ => "其他"
  }

  def sequenceMathTest() = {
    println(sequenceMatch(List(5, 8, 9)))
    println(sequenceMatch(List(5, 8, 9, 1)))
    println(sequenceMatch(List(1, 5, 8, 9)))
  }

输出结果

匹配5元素开头的三元素列表
其他
匹配以1开头任意数目的列表

3.构造器匹配

def constructorMatch(x: Person): String = x match {
    case Person("tom", 12) => "name:tom,age:12"
    case Person(first, 49) => s"name:$first,age:49"
    case _ => "other"
  }

  def constructorMatchTest() = {
    println(constructorMatch(Person("tom", 12)))
    println(constructorMatch(Person("tom", 49)))
    println(constructorMatch(Person("tom", 49)))
  }

输出结果

name:tom,age:12
name:tom,age:49
name:tom,age:49

4.元组匹配

def tupleMatch(x: Any): String = x match {
    case (a, b) => s"匹配二元组,元素为$a,$b"
    case (a, b, c) => s"匹配三元组,元素为$a,$b,$c"
    case _ => "other"
  }

  def tupleMatchTest() = {
    println(tupleMatch(Tuple2(1, 2)))
    println(tupleMatch(Tuple3(1, 2, 3)))
  }

输出结果

匹配二元组,元素为1,2
匹配三元组,元素为1,2,3

5.类型匹配

def typeMatch(x: Any): String = x match {
    case s: String => s"字符串类型匹配 $s"
    case s: Int => s"整形匹配 $s"
    case Person(name, age) => s"string type match $name,$age"
    case _ => "other"
  }

  def typeMatchTest() = {
    println(typeMatch("字符串"))
    println(typeMatch(5))
    println(Person("tom", 25))
  }

运行结果

字符串类型匹配 字符串
整形匹配 5
Person(tom,25)

if模式匹配 约束

利用if语句附加更多的条件达到更细致的模式匹配

def ifMatch(x: (Int, Int)): String = x match {
    case (x1, x2) if x2 == 0 => s"非法的分数表示"
    case (x1, x2) => s"合法的分数表示:$x1/$x2"
  }

  def ifMatchTest() = {
    println(ifMatch(2, 0))
    println(ifMatch(3, 8))
  }

运行结果

非法的分数表示
合法的分数表示:3/8
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值