scala - 如何在 Scala 2.13 中对存在类型执行安全模式匹配?

标签 scala pattern-matching type-safety existential-type scala-2.13

注意:这是一个人为的示例。

考虑以下存在类型。

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)
}

但是模式匹配会分别推断 showvalue 的类型为 Any => StringAny。因此,我还可以定义一个 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/

相关文章:

scala - 无法在 com.a.y.x 中访问包 x 中的类 SomeClass

scala - 具有依赖类型的工厂方法

C++ 中的 Python 样式变量

ruby - 我应该在 Ruby 中验证方法参数吗?

scala - 如何从 Scala 中的泛型函数返回 null?

scala - Spark textFile 与 WholeTextFiles

windows - 如何使用 Windows 命令在文本文件中查找字符串并复制接下来的 5 个字符

Ruby Kernel::system,shell 命令中的否定模式未按预期工作

sockets - Erlang 变量模式匹配

c++ - 在 C++ 中键入安全(r)位标志?