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