受适当类型限制的类型构造函数
Type constructor bounded by proper type
考虑
中的以下类型参数子句[F[_] <: Int]
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
的一个例子是总是 returns Int
:
type ConstInt[X] = Int
h[ConstInt] // compiles
请注意,您可以在 _
中命名类型。例如。我可以声明一个类型参数F[X] <: X
。 X
是局部声明,通过出现在左侧的 F
下定义,用作右侧的边界,然后超出范围。这个例子意味着 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)
也许这让我们明白了界限的含义。
考虑
中的以下类型参数子句[F[_] <: Int]
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
的一个例子是总是 returns Int
:
type ConstInt[X] = Int
h[ConstInt] // compiles
请注意,您可以在 _
中命名类型。例如。我可以声明一个类型参数F[X] <: X
。 X
是局部声明,通过出现在左侧的 F
下定义,用作右侧的边界,然后超出范围。这个例子意味着 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)
也许这让我们明白了界限的含义。