scala - 带或不带 '_' 的高级类型构造函数

标签 scala types higher-kinded-types

此签名声明了更高种类的类型:

case class MyContainer[A, M[_]](el: M[A])

现在,我可以创建它的实例:

scala> val mc1 = MyContainer[Int, Option](Some(3))
mc1: MyContainer[Int,Option] = MyContainer(Some(3))

我还可以将 MyContainer 声明为:

case class MyContainer[A, M[A]](el: M[A])

生成与mc1相同的实例:

mc1: MyContainer[Int,Option] = MyContainer(Some(3))

这些方法之间有什么区别以及何时应使用哪些方法?

最佳答案

根据语言规范(§4.4 类型参数),这些是等效的:

[M[X], N[X]]
[M[_], N[_]] // equivalent to previous clause

本段描述了此语法背后的推理:

Higher-order type parameters (the type parameters of a type parameter t) are only visible in their immediately surrounding parameter clause (possibly including clauses at a deeper nesting level) and in the bounds of t. Therefore, their names must only be pairwise different from the names of other visible parameters. Since the names of higher-order type parameters are thus often irrelevant, they may be denoted with a _, which is nowhere visible.

请注意,在这种情况下,M[A] 中的 A 将被忽略。它可以是 T 并且它也可以工作:

scala> case class MyContainer[A, M[T]](el: M[A])
defined class MyContainer

scala> val mc1 = MyContainer[Int, Option](Some(3))
mc1: MyContainer[Int,Option] = MyContainer(Some(3))

为了防止混淆,我总是使用 [_],或者至少不会重复使用这些名称。

关于scala - 带或不带 '_' 的高级类型构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26204738/

相关文章:

scala - 我有一个 Scala 列表,如何获得 TraversableOnce?

scala - 在 Play 中获取当前循环的索引! 2 Scala 模板

haskell - 隐式提升的正确性

python - 如何在类型提示系统中使用通用(高级)类型变量?

scala - sbt,publishLocal,解决错误

javascript - TypeScript 中导入模块的增强类型

c++ - 数组下标的无效类型 'double [100][double]'

scala - 更高种类的类型什么时候有用?

scala - 多态类型的类型类遭受类型删除

Scala:Cats、OptionT[Future, T] 和 ApplicativeError