`
bit1129
  • 浏览: 1049002 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

【Scala十一】Scala核心五:case模式匹配

 
阅读更多
package spark.examples.scala.grammars.caseclasses

object CaseClass_Test00 {

  def simpleMatch(arg: Any) = arg match {
    case v: Int => "This is an Int"
    case v: (Int, String) => ("This is a (Int, String): " + v._1 + "," + v._2)
    case _ => ("Unknown type, print as is: " + _) //模糊匹配,匹配所有的情况,类似*
  }

  def caseClassMatch(arg: Any) = arg match {
    case Dog(_) => arg
    case Cat(_) => arg
    case Horse(n, a, w) => w
  }

  def constantMatch(arg: Any) = arg match {
    case 3 => "This is an Int 3"
    case "3" => "This is a string 3"
    case true => "This is boolean true"
    case Nil => "This is a Nil"
    case null => "This is null"
  }

  def partialMatch(arg: List[_]) = arg match {
    case List(0, _, _) => "This is a list of length 3, and also starts with 0"
    case List(0, _*) => "This is a list of length not 3, and starts with 0: " + arg.size
  }

  def tupleMatch(arg: Any) = arg match {
    case (k, v) => "Tuple2: " + k + "," + v
    case (k, v, w) => "Tuple3: " + k + "," + v + "," + w
  }

  def typeMatch(arg: Any) = arg match {
    case v: Int => "Int:" + v
    case m: Map[_, _] => "Map:" + m.size
    case t: (_, _) => "Tuple2: " + t._1 + "," + t._2
    case _ => "Unknown type:" + arg
  }

  def typeEraseMatch(arg: Any) = arg match {
    case m: Map[Int, Int] => "Map from Int to Int:" + m.size
    case l: List[Int] => "Int List: " + l.size
    case t: (String, String) => "String tuple" + t._1
  }

  def arrayTypeEraseMatch(arg: Any) = arg match {
    case ia: Array[Int] => "Int Array: " + ia.length
    case sa: Array[String] => "String List: " + sa.length
  }

  def precedenceMatch(arg: Any) = arg match {
    case e: IllegalArgumentException => "This is an IllegalArgumentException"
    case e: Exception => "This is an Exception."
  }

  def optionMatch(arg: Option[_]) = arg match {
    case Some(s) => s
    case None => "?"
  }


  //等同于 abstract class Animal { /*empty body*/}
  abstract class Animal

  //1. 无参的case class已经deprecated
  //2. name默认成为case class的val field
  //3. 无需new Cat("kitty")
  //4.可以copy进行构造一个全新的case class,只有部分属性不同的情况很合适
  //5. match/case匹配,match/case class匹配,=>用于分隔模式和模式匹配结果的表达式
  //6. match/case匹配,match/case class匹配,case中的属性值,可以使用变量指代或者_指代
  //7. case _ => expr,表达的是模糊匹配或者任意匹配
  //8.常量匹配
  //9. List匹配
  //10. Tuple匹配
  //11.类型匹配
  //12. 集合元素的类型运行时擦除:List,Map,Tuple,不包括数组
  //13. 数组元素类型运行时不檫除
  //14.匹配优先级,类似switch/case+break
  //15. Option
  case class Cat(name: String) extends Animal

  case class Dog(name: String) extends Animal

  case class Horse(name: String, age: Int, weight: Double)

  def main(args: Array[String]) {
    println(Cat("kitty"))
    println(Cat("kitty").name)
    println(new Dog("carl"))
    val h1 = Horse("H", 8, 121.1)
    val h2 = h1.copy(name = "X")
    println(h2)

    println(simpleMatch(100))
    println(simpleMatch(100, "200"))

    println(caseClassMatch(Dog("Carl")))
    println(caseClassMatch(Horse("H", 11, 222.2)))

    //常量匹配
    println(constantMatch(3))
    println(constantMatch(1 == 1))
    println(constantMatch("3"))
    println(constantMatch(null))
    println(constantMatch(Nil)) //Nil表示空List

    //部分匹配
    println(partialMatch(List(0, 1, 2)))
    println(partialMatch(List(0, 1, 2, 3)))

    //元组匹配
    println(tupleMatch(1, 2))
    println(tupleMatch("One", "Tow", "Three"))

    //类型匹配
    println(typeMatch(100))
    println(typeMatch(Map(1 -> 2, 2 -> 3)))
    println(typeMatch(("One", "Two")))
    println(typeMatch(("One", "Two", "Three"))) //Unknown type

    //类型的运行时擦除:List,Map,Tuple
    println(typeEraseMatch(Map(1 -> 1, 2 -> 2))) //匹配m成功
    println(typeEraseMatch(Map("One" -> "One", "Two" -> "Two"))) //匹配m成功

    println(typeEraseMatch(List(1, 2, 3))) //匹配l成功
    println(typeEraseMatch(List("One", "Two", "Three"))) //匹配l成功

    println(typeEraseMatch((1, 1))) //匹配t成功
    println(typeEraseMatch(("One", "One"))) //匹配t成功

    println(arrayTypeEraseMatch(Array(1, 2))) //匹配ia成功
    println(arrayTypeEraseMatch(Array("One", "Two"))) //匹配sa成功

    println(precedenceMatch(new IllegalArgumentException()))
    println(precedenceMatch(new NullPointerException()))

    //Option匹配
    println(optionMatch(Map("One"->"Two").get("One"))) //Two
    println(optionMatch(Map("One"->"Two").get("1"))) //?
  }

}

 

A case class is a simple type of immutable class that comes with implementations of all of the basic Java class methods, like toString, equals, and hashCode, which makes them very easy to use

分享到:
评论

相关推荐

    scala的匹配集合

    scala中的模式匹配,还能用来匹配集合。 匹配数组 示例说明 依次修改代码定义以下三个数组 Array(1,x,y) // 以1开头,后续的两个元素不固定 Array(0) // 只匹配一个0元素的元素 Array(0, …) // 可以任意数量,但是...

    Scala程序设计(第2版)

    4.13 总结关于模式匹配的评价 111 4.14 本章回顾与下一章提要 111 第5章 隐式详解 112 5.1 隐式参数 112 5.2 隐式参数适用的场景 115 5.2.1 执行上下文 115 5.2.2 功能控制 115 5.2.3 限定...

    Scala助手StreamyJ.zip

    StreamyJ 使得用 Jackson 编写 Scala 解析器变的简单了:将 JsonToken 常量转换成 case classes(Scala 的一种模式匹配),并允许类型匹配。 提供了一种机制——允许部分解析器有权对特定的已解析的项目采取措施。 ...

    scala学习手册.zip

    Scala也是一种函数式语言,其函数也能当成值来使用。Scala提供了轻量级的语法用以定义匿名函数,支持高阶函数,允许...Scala的Case Class及其内置的模式匹配相当于函数式编程语言中常用的代数类型(Algebraic Type)。

    scala的匹配样例类

    scala可以使用模式匹配来匹配样例类,从而可以快速获取样例类中的成员数据。后续,我们在开发Akka案例时,还会用到。 示例 需求说明 创建两个样例类Customer、Order Customer包含姓名、年龄字段 Order包含id字段 ...

    积分java源码-match-block:[ABANDONED]模式匹配块作为值

    模式匹配块作为值。 ![数据所有的东西]() 将抽象转化为一流的值使我们能够对它们进行抽象和组合,并且通常会产生概念上更简单的模型。 一流的东西一直是 Clojure 的一个共同主题,在那里它被亲切地称为“数据所有的...

    scala-enum:基于密封类的 Scala 枚举的简单 40 行实现

    这是基于密封类(支持模式匹配耗尽检查)的枚举的简单 40 行实现。 它使用反射,因此如果您使用它,您可能需要将libraryDependencies += "org.scala-lang" % "scala-reflect" % scalaV到您的项目中。 对象的枚举 ...

    快学 scala 中文版 带完整目录

    第14章 模式匹配和样例类 A2 221 14.1 更好的switch 222 14.2 守卫 223 14.3 模式中的变量 223 14.4 类型模式 224 14.5 匹配数组、列表和元组 225 14.6 提取器 227 14.7 变量声明中的模式 227 14.8 for...

    4.样式类和模式匹配1

    1. 样例类 case class 和模式匹配 pattern matching 是一组孪生语法,它们为我们编写规则的、 1. 样例类是 Scala 用于对象模

    message-schemas.scala:Scala 库,包含 Blinkbox Books 消息的强类型模式版本

    要解构EventBody您可以使用模式匹配,这将根据媒体类型选择适当的消息类,例如: body match { case MyEvent (info) => println(info) case _ => println( " unexpected message " ) } 修改消息类别 一旦服务...

    MyScala.rar

    Scala _02基础,Scala _03方法与函数,Scala _04Scala字符串,Scala _05集合_数组,Scala _07trait特性,Scala _08模式匹配match&偏函数,Scala _09样例类(case classes)&隐式转换,Scala _10Actor Model

    kaleidoscope:对正则表达式进行静态检查的内联匹配

    然后,您可以在任何位置使用Scala中的模式,使用万花筒正则表达式(以字母r开头的字符串)。 例如, path match case r " /images/.* " => println( " image " ) case r " /styles/.* " => println( " stylesheet...

    any:Any 类型,模仿 Scala 的 Any 类型

    这是 Scala 的 Any 类型的玩法,主要用于模式匹配类型技术。 学分 感谢允许我重新调整 gem Any用途! 原始版本将在0.0.1 和 0.0.2 版本中维护 用法 请注意,我在这里使用 Qo。 如果在 Ruby 2.6+ 中添加这两个...

    casematch:Java 8的Matcher库

    该库将不提供像从功能语言(或具有更多功能方面的语言)(例如Scala)中已知的模式匹配一​​样强大和紧凑的匹配。 尤其是缺少对象分解,可能永远无法提供。 目标始终是找到Java开发中常见情况的可读表示。 以下...

Global site tag (gtag.js) - Google Analytics