Scala Tagging Traits & Case Objects

本文介绍Scala中的标记特性,通过定义密封特质Animal并列举其具体实例如Panda、Tiger和Lion来展示如何使用标记特性进行类型组织。此外,文章还提供了一个简单的应用示例,演示了如何使用模式匹配来处理这些标记类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原创转载请注明出处: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编程思想

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值