存在已弃用的密封特征实例时的详尽模式匹配
Exhaustive pattern matching when deprecated sealed trait instance present
假设以下场景
sealed trait Status
case object Active extends Status
case object Inactive extends Status
@scala.deprecated("deprecated because reasons")
case object Disabled extends Status /
考虑到 Disabled
无法删除对象并给定 val status: Status = getStatus
存在以下任一问题:
- 匹配不详尽失败:
status match {
case Active => ???
case Inactive => ???
}
- 使用已弃用的值失败
status match {
case Active => ???
case Inactive => ???
case Disabled => ???
}
- 失去编译时安全性
status match {
case Active => ???
case Inactive => ???
case _ => ???
}
这种场景下能实现类型安全的穷举匹配吗?
我认为选项 2 是可行的方法。但要使其正常工作,您必须有选择地禁用警告。支持以 Scala 2.13.2 and 2.12.13
开头
@annotation.nowarn("cat=deprecation")
def someMethod(s: Status) = s match {
case Active => "Active"
case Inactive => "Inactive"
case Disabled => "Disabled"
}
此处“已弃用”和“不可用”之间可能有些混淆。
Disabled
值为 deprecated
,但仍然可用。并且由于它仍然可用,因此代码中必须仍然支持它,因为它仍然可以使用。所以选项 2 是唯一可以接受的解决方案,因为它是唯一可以在类型安全的情况下适当处理 Disabled
的解决方案。选项 1 不处理 Disabled
,选项 3 失去类型安全。
另请注意,none 这些代码示例“失败”,它们只是生成警告。所以解决方案是按照其他答案中的描述抑制弃用警告。
假设以下场景
sealed trait Status
case object Active extends Status
case object Inactive extends Status
@scala.deprecated("deprecated because reasons")
case object Disabled extends Status /
考虑到 Disabled
无法删除对象并给定 val status: Status = getStatus
存在以下任一问题:
- 匹配不详尽失败:
status match {
case Active => ???
case Inactive => ???
}
- 使用已弃用的值失败
status match {
case Active => ???
case Inactive => ???
case Disabled => ???
}
- 失去编译时安全性
status match {
case Active => ???
case Inactive => ???
case _ => ???
}
这种场景下能实现类型安全的穷举匹配吗?
我认为选项 2 是可行的方法。但要使其正常工作,您必须有选择地禁用警告。支持以 Scala 2.13.2 and 2.12.13
开头@annotation.nowarn("cat=deprecation")
def someMethod(s: Status) = s match {
case Active => "Active"
case Inactive => "Inactive"
case Disabled => "Disabled"
}
此处“已弃用”和“不可用”之间可能有些混淆。
Disabled
值为 deprecated
,但仍然可用。并且由于它仍然可用,因此代码中必须仍然支持它,因为它仍然可以使用。所以选项 2 是唯一可以接受的解决方案,因为它是唯一可以在类型安全的情况下适当处理 Disabled
的解决方案。选项 1 不处理 Disabled
,选项 3 失去类型安全。
另请注意,none 这些代码示例“失败”,它们只是生成警告。所以解决方案是按照其他答案中的描述抑制弃用警告。