注意:这是一个人为的示例。
考虑以下存在类型。
sealed trait Showable
final case class Show[A](show: A => String, value: A) extends Showable
我可以定义一个 show
方法,如下所示:
def show(showable: Showable): String = showable match {
case Show(show, value) => show(value)
}
但是模式匹配会分别推断 show
和 value
的类型为 Any => String
和 Any
。因此,我还可以定义一个 show
方法,如下所示:
def show(showable: Showable): String = showable match {
case Show(show, value) => show(42)
}
这是不安全的。如何确保 case 表达式 show
只能应用于 value
?
最佳答案
如果您匹配键入的模式,则
def show(showable: Showable): String = showable match {
case s: Show[a] => s.show(s.value)
}
或
def show(showable: Showable): String = showable match {
case s: Show[_] => s.show(s.value)
}
编译但是
def show(showable: Showable): String = showable match {
case s: Show[a] => s.show(42)
}
//type mismatch;
// found : Int(42)
// required: a
或
def show(showable: Showable): String = showable match {
case s: Show[_] => s.show(42)
}
//type mismatch;
// found : Int(42)
// required: _
没有。
关于scala - 如何在 Scala 2.13 中对存在类型执行安全模式匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75721211/