Scala

scala-24-样例类

2020-04-17  本文已影响0人  chen_666

基本介绍

object CaseClassDemo02 {
  def main(args: Array[String]): Unit = {
    //该案例的作用就是体验使用样例类方式进行对象匹配简洁性
    for (amt <- Array(Dollar2(1000.0), Currency2(1000.0, "RMB"), NoAmount2)) {
      val result = amt match {
        //说明
        case Dollar2(v) => "$" + v // $1000.0
        //说明
        case Currency2(v, u) => v + " " + u // 1000.0 RMB
        case NoAmount2 => "" // ""
      }
      println(amt + ": " + result)
    }
  }
}

abstract class Amount2
case class Dollar2(value: Double) extends Amount2    //样例类
case class Currency2(value: Double, unit: String) extends Amount2 //样例类
case object NoAmount2 extends Amount2  //样例类

克隆

object CaseClassDemo03 {
  def main(args: Array[String]): Unit = {
    val amt = new Currency3(3000.0,"RMB")
    val amt2 = amt.copy() // 克隆,创建的对象和amt的属性一样
    println("amt2.value" + amt2.value + " amt2.unit= " + amt2.unit)
    println(amt2)

    val amt3 = amt.copy(value = 8000.0)
    println(amt3)

    val amt4 = amt.copy(unit = "美元")
  }
}


abstract class Amount3
case class Dollar3(value: Double) extends Amount3    //样例类
case class Currency3(value: Double, unit: String) extends Amount3 //样例类
case object NoAmount3 extends Amount3  //样例类
上一篇 下一篇

猜你喜欢

热点阅读