[英]Type constructor bounded by proper type
考虑以下类型参数子句[F[_] <: Int]
in
def h[F[_] <: Int] = ???
其中类型构造函数F
由正确的类型Int
限制。 现在h[List]
和h[Int]
都是非法的
scala> def h[F[_] <: Int] = ???
|
def h[F[_] <: Int]: Nothing
scala> h[List]
^
error: type arguments [List] do not conform to method h's type parameter bounds [F[_] <: Int]
scala> h[Int]
^
error: Int takes no type parameters, expected: 1
那么为什么[F[_] <: Int]
是合法的?
类型参数声明F[_] <: Int
意味着F
的每个实例化都必须是Int
的子类型。 它在语法上是正确的,虽然很神秘: F
不必是Int
的子类型; F[_]
必须是Int
的子类型(对于所有可能放在_
中的类型)。 这种F
的一个示例是始终返回Int
的示例:
type ConstInt[X] = Int
h[ConstInt] // compiles
请注意,您可以在_
中命名类型。 例如,我可以声明一个类型参数F[X] <: X
。 X
是声明的局部变量,定义为出现在左侧的F
下方,用作右侧的边界,然后离开 scope。 此示例意味着F[X]
必须是X
的子类型,例如
def f[F[X] <: X] = ???
type Identity[X] = X
f[Identity] // works
type ConstNothing[X] = Nothing
f[ConstNothing] // works
// f[ConstInt] (ConstInt[X] = Int is not always a subtype of X; counterexample X = AnyRef)
也许这让我们明白了界限应该意味着什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.