繁体   English   中英

由正确类型限制的类型构造函数

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM