Scala匹配case语句中的任何枚举值

时间:2017-04-24 18:11:02

标签: scala

我定义了一个scala枚举:

object SalesChannelType extends scala.Enumeration {
  type SalesChannelType = Value
  val SALES_CHANNEL_1, SALES_CHANNEL_2 = Value
}

class SalesChannelType extends TypeReference[SalesChannelType.type]

现在我想编写一个匹配语句,在单个案例中匹配任何枚举值,如:

SalesChannelType.SALES_CHANNEL_1 match {
    case SalesChannelType => println(_)
    case _ => println("specified sales channel does not exist")

如果在枚举中定义了销售渠道,那么第一个案例陈述就是打印销售渠道。否则,应调用第二个case语句。目前上面的代码不会使用错误Pattern type is incompatible with expected type, found SalesChannel.type required SalesChannel.Value

进行编译

1 个答案:

答案 0 :(得分:1)

我认为这是你正在寻找的东西(虽然@Jasper-M的评论是正确的 - 如果程序输入得体,那就没用了):

SalesChannelType.SALES_CHANNEL_1 match {
  case s: SalesChannelType.Value => println(s)
  case _ => println("specified sales channel does not exist")
}