簡體   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