Scala 模式匹配

通配符匹配

object All_Match {

  def wildcardPattern(x:String):String= x match {
    case _ => "other"
  }

  def main(args: Array[String]): Unit = {
    println(wildcardPattern("hello"))
  }

}

常量匹配

object All_Match {

  def constantPattern(x:Any):String= x match {
    case 1 => "one"
    case true => "true"
    case "hello" => "hello"
    case Nil => "an empty list"
  }

  def main(args: Array[String]): Unit = {
    println(constantPattern(1))
    println(constantPattern(true))
    println(constantPattern("hello"))
    println(constantPattern(List()))
  }

}

变量匹配

变量模式匹配很像通配符模式匹配,唯一的区别在于:使用通配符模式匹配时,你不能在case推导符后面使用匹配到的值,但是变量模式匹配给匹配到的值命名了一个变量名,因此你可以在推导符后面使用它

ef variablePattern(x:Any):String= x match {
    case i:Int => s"one is ${i}"
    case otherValue => s"the value is ${otherValue}"
  }

  def main(args: Array[String]): Unit = {
    println(variablePattern(1))
    println(variablePattern("XXX"))
  }

构造函数匹配

case class Person(firstName:String,lastName:String)
case class Dog(name:String)

object All_Match {

  def constructorPattern(x:Any):String= x match {
    case Person(first,last) => "this is person"
    case Person(first,"alex") => "this is alex"
  }

  def main(args: Array[String]): Unit = {
    println(constructorPattern(Person("","")))
    println(constructorPattern(Person("","alex")))
  }

}

集合类匹配

object All_Match {

  def sequencePattern(x:Any):String= x match {
    case List("hello",_,_) => "three element;start with hello"
    case List("world",_*) => "start with world"
    case Vector(_,2,_*) => "the second element is 2"
  }

  def main(args: Array[String]): Unit = {
    println(sequencePattern(List("hello","","")))
    println(sequencePattern(List("world","")))
    println(sequencePattern(Vector("",2,"","")))
  }

}

元组匹配

object All_Match {

  def tuplesPattern(x:Any):String= x match {
    case (a,b) => s"the tuple is ${a},${b}"
    case (1,b,c) => s"the tuple start with 1 ${b},${c}"
  }

  def main(args: Array[String]): Unit = {
    println(tuplesPattern((2,3)))
    println(tuplesPattern((1,2,3)))
  }

}

类型匹配

case class Dog(name:String)

object All_Match {

  def typePattern(x:Any):String= x match {
    case str:String => "this is String type"
    case str:Boolean => "this is Boolean type"
    case str:Dog => "this is Dog type"
    case list:List[_] => "this is List type"
    case map:Map[_,_] => "this is Map type"
  }

  def main(args: Array[String]): Unit = {
    println(typePattern(""))
    println(typePattern(true))
    println(typePattern(Dog("haha")))
    println(typePattern(List()))
    println(typePattern((Map())))
  }

}

模式匹配附加约束

object All_Match {

  def guardPattern(x:Any):Any= x match {
    case (a:Int,b:Int) if a ==b => a*b
      case(a:Int,b:Int) => a+b
  }

  def main(args: Array[String]): Unit = {
    println(guardPattern((1,2)))
    println(guardPattern((1,1)))
  }

}

Sealed Classe与模式匹配

如果一个类被声明为sealed,则除了在定义这个class的文件内你可以创建它的子类之外,其他任何地方都不允许一个类去继承这个类。在进行模式匹配时,我们需要时刻留心你的case语句是否能cover所有可能的情形,但如果在匹配一个类族特别是子类时,可能会出现无法控制的情况,因为如果类族是可以自由向下派生的话,过去覆盖了各种情形的case语句就可能不再“全面”了。所以使用sealed class是对模式匹配一种保护。另外,使用sealed class还可以从编译器那边得到一些额外的好处:当你试图针对case继承自sealed class的case类进行模式匹配时,如果漏掉了某个某些case类,编译器在编译时会给一个warning. 所以说:当你想为一模式匹配而创建一个类族时,或者说你的类族将要被广发使用于模式匹配时,你最好考虑将你的类族超类限定为sealed

sealed abstract class Expr
case class Var(name: String) extends Expr
case class Number(num: Double) extends Expr

object All_Match {

  def sealdPattern(e: Expr): String = e match {
    case Number(_) => "a number"
//    case Var(_) => "a variable"
  }

  def main(args: Array[String]): Unit = {
    println(sealdPattern(Number(12)))
  }

}

编译时的警告:Warning:(9, 39) match may not be exhaustive. It would fail on the following input: Var(_) def sealdPattern(e: Expr): String = e match {


变量定义中的模式匹配

  • 从元组中提取变量
    object All_Match {
    
    
      def main(args: Array[String]): Unit = {
        
        //从元组中提取变量
        val (a,b) = ("hello","world")
        println(s"a is ${a}")
    
      }
    
    }
    
  • 从构造器中提取额变量
    case class Person(name:String,age:Int)
    
    object All_Match {
    
    
      def main(args: Array[String]): Unit = {
    
        //从构造器中提取变量
        val Person(name,age) = Person("zhangsan",23)
    
        println(s"the name is ${name}")
    
      }
    
    }
    
  • main函数中提取参数
    object All_Match {
    
    
      def main(args: Array[String]): Unit = {
    
        val Array(arg1,arg2) = args
        println(s"${arg1}")
    
      }
    
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值