当存在已弃用的密封特征实例时进行详尽的模式匹配

m3t*_*man 5 scala pattern-matching

假设以下场景

sealed trait Status

case object Active extends Status
case object Inactive extends Status
@scala.deprecated("deprecated because reasons")
case object Disabled extends Status /
Run Code Online (Sandbox Code Playgroud)

考虑到Disabled对象无法被删除并且val status: Status = getStatus存在以下问题之一:

  1. 匹配不详尽而失败:
status match {
  case Active => ???
  case Inactive => ???
}
Run Code Online (Sandbox Code Playgroud)
  1. 使用已弃用的值而失败
status match {
  case Active => ???
  case Inactive => ???
  case Disabled => ???
}
Run Code Online (Sandbox Code Playgroud)
  1. 失去编译时安全性
status match {
  case Active => ???
  case Inactive => ???
  case _ => ???
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下可以实现类型安全穷举匹配吗?

Iva*_*iuc 5

我认为选项 2 是最佳选择。但要使其正常工作,您必须有选择地禁用警告。从Scala 2.13.2 和 2.12.13开始支持此功能

@annotation.nowarn("cat=deprecation")
def someMethod(s: Status) = s match {
  case Active   => "Active"
  case Inactive => "Inactive"
  case Disabled => "Disabled"
}

Run Code Online (Sandbox Code Playgroud)