简体   繁体   English

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

[英]Type constructor bounded by proper type

Consider the following type parameter clause [F[_] <: Int] in考虑以下类型参数子句[F[_] <: Int] in

def h[F[_] <: Int] = ???

where a type constructor F is bounded by the proper type Int .其中类型构造函数F由正确的类型Int限制。 Now both h[List] and h[Int] are illegal现在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

so why is then [F[_] <: Int] legal?那么为什么[F[_] <: Int]是合法的?

The type parameter declaration F[_] <: Int means that every instantiation of F must be a subtype of Int .类型参数声明F[_] <: Int意味着F的每个实例化都必须是Int的子类型。 It's right in the syntax, though cryptic: F does not have to be a subtype of Int ;它在语法上是正确的,虽然很神秘: F不必是Int的子类型; F[_] has to be a subtype of Int (for all types that may be placed in the _ ). F[_]必须是Int的子类型(对于所有可能放在_中的类型)。 An example of such an F is one which always returns Int :这种F的一个示例是始终返回Int的示例:

type ConstInt[X] = Int
h[ConstInt] // compiles

Note that you can name the type in the _ .请注意,您可以在_中命名类型。 Eg I can declare a type parameter F[X] <: X .例如,我可以声明一个类型参数F[X] <: X X is local to the declaration, defined by appearing under F on the left, used as a bound on the right, and going out of scope afterwards. X是声明的局部变量,定义为出现在左侧的F下方,用作右侧的边界,然后离开 scope。 This example means that F[X] must be a subtype of X , eg as in此示例意味着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)

Perhaps that drives home what the bound is supposed to mean.也许这让我们明白了界限应该意味着什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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