Scala基础应用(4)- 样本类和模式匹配

时间:2022-05-30 06:59:49

Scala基础应用(4)- 样本类和模式匹配

样本类

就是在普通类前加了case

case class Test(param1: Int, param2: String ...) {
}

样本类带来的好处

  1. 省略掉new, 样本类实例化不需要在前面加new, 直接产生对象。
  2. 参数自动加val, 即样本类的参数缺省是不可修改的
  3. 自动加上toString, equals, hashcode三个方法
  4. 之所以可以省略new, 是因为Scala为样例类自动创建一个包含了apply和unapply的伴生类

模式匹配

  1. 模式在变量定义中

    val myTuple = (123, "abc")
    val (aNumber, aString) = myTuple

    声明两个变量及其值:
    aNumber = 133
    aString = "abc"
  2. for表达式里的模式

    1
    var capitals = Map[String, String]("China" -> "BeiJing", "France" -> "Paris")
    for ((country, city) <- capitals)
    println(s"The capital of ${country} is ${city}")

    2:
    val results = List(Some("apple"), None, Some("orange"))
    for (Some(fruit) <- results) print(fruit)

    结果为
    apple
    orange

    正如你看到的,for表达式模式还可以过滤掉不匹配的值。
  3. 偏函数模式

    val withDefault: Option[Int] => Int = {
    case Some(x) => x
    case None => 0
    }
  4. match

    4.1 通配模式

    • 样式
    变量 match {
    case 指定匹配值 =>
    case _ => // 通配模式
    }

    4.2 简单模式种类

    • 常量
    val x = 5
    val result = x match {
    case 5 => "five"
    }

    val x = 5
    val y = 5
    val result = x match {
    case `y` => "five"
    }
    • 变量
    val x = 5
    val y = 5
    val result = x match {
    case y => "five"
    }
    • 构造器
    case class Test(x: Int)

    val test1 = Test(5)
    val result = test1 match {
    case Test(5) => "five"
    case _ =>
    }
    • 序列模式
    1:
    val lst1 = List(0, 1, 2)
    val result = lst1 match {
    case List(0, _, _) => "3 values"
    case _ =>
    }

    2:
    val lst1 = List(0, 1, 2)
    val result = lst1 match {
    case List(0, _*) => "3 values"
    case _ =>
    }
    • 元组模式
    val tuple1 = (1, 2, 3)
    val result = tuple1 match {
    case (a, b, c) => "threee values"
    case _ =>
    }
    • 类型模式
    val str = "this is a string"
    val result = str match {
    case s: String => "match"
    case _ =>
    }
    • 绑定变量
    val x = 5
    val result = x match {
    case y @ 5 => y + "five"
    }
    • 模式守卫
    val str = "this is a string"
    val result = str match {
    case s: String if s(0) == 't' => "match"
    case _ =>
    }
    • 模式重叠
    val str = "this is a string"
    val result = str match {
    case s: String if s(0) == 't' => "match 0"
    case s: String if s(1) == 'h' => "match 1"
    case _ =>
    }

4.3 封闭类

  • 声明封闭类
sealed abstract class Expr
case class Var(name: String) extends Expr
case class Number(num: Double) extends Expr
case class UnOp(operator: String, arg: Expr) extends Expr
case class BinOp(operator: String, left: Expr, right: Expr) extends Expr
  • 模式匹配
def describe(e: Expr) : String = e match {
case Number(_) => "a number"
case Var(_) => "a variable"
}

上面声明在编译时会出现警告,是的,编译器将检查封闭类所有可能的值是否都做了匹配