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存在以下问题之一:
status match {
case Active => ???
case Inactive => ???
}
Run Code Online (Sandbox Code Playgroud)
status match {
case Active => ???
case Inactive => ???
case Disabled => ???
}
Run Code Online (Sandbox Code Playgroud)
status match {
case Active => ???
case Inactive => ???
case _ => ???
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下可以实现类型安全穷举匹配吗?
我认为选项 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)
| 归档时间: |
|
| 查看次数: |
194 次 |
| 最近记录: |