Scala sample class pattern matching

Relatively simple, go directly to the code.

package scalapackage.scalamatch

import scala.util.Random

/**
  * Created by Germmy on 2018/4/29.
  */
object TestCaseClass {
  def main(args: Array[String]) {
    val products: Array[Product with Serializable] = Array(Hearbeat(1000),SubmitTask("1000","task-1000"),ChecktoutTime)//这个地方的对象竟然不用new就可以放进去
    val products1: Product with Serializable = products(Random.nextInt(products.length))
    products1 match {//拿到值后直接Match
      case Hearbeat(time)=>println("Hearbeat")
      case SubmitTask(id,name)=>println("SubmitTask")
      case ChecktoutTime=>println("ChecktoutTime")
    }
  }
}

case class Hearbeat(time:Long)
case class SubmitTask(id:String,name:String)
case object ChecktoutTime

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325107340&siteId=291194637