此签名声明了更高种类的类型:
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 oft
. 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/