Scala Tagging Traits & Case Objects

原创转载请注明出处:http://agilestyle.iteye.com/blog/2334895

标记特征是一种将类或对象组织到一起的方式

package org.fool.scala.traits

sealed trait Animal

case object Panda extends Animal

case object Tiger extends Animal

case object Lion extends Animal

object Animal {
  val values = Vector(Panda, Tiger, Lion)
}

object TaggingTrait extends App {
  def display(a: Animal) = a match {
    case Panda => s"It's $a"
    case Tiger => s"It's $a"
    case Lion => s"It's $a"
  }

  println(Animal.values.map(display))
}

Note:

The hallmark of a tagging trait (Color, in this case) is that it only exists to collect types under a common name, thus it typically has no fields or methods.The sealed keyword on line 4 tells Scala “there are no subtypes of Color other than the ones you see here” (all subtypes of a sealed class must live in the same source file). Scala warns you that a “match may not be exhaustive” if you don’t cover all the cases. e.g.

...

object TaggingTrait extends App {
  def display(a: Animal) = a match {
    case Panda => s"It's $a"
    case Tiger => s"It's $a"
    //case Lion => s"It's $a"
  }

  println(Animal.values.map(display))
}

Console Output


 

Console Output

case对象就像case类一样,只是它产生的是对象而不是类。当case对象转换为String时,将会获得模式匹配的好处以及友好输出。


 

参考资料:

Scala编程思想

猜你喜欢

转载自agilestyle.iteye.com/blog/2334895
今日推荐