原创转载请注明出处: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编程思想
Scala标记特性实践
本文介绍Scala中的标记特性,通过定义密封特质Animal并列举其具体实例如Panda、Tiger和Lion来展示如何使用标记特性进行类型组织。此外,文章还提供了一个简单的应用示例,演示了如何使用模式匹配来处理这些标记类型。

被折叠的 条评论
为什么被折叠?



