【问题标题】:Type constructor bounded by proper type由正确类型限制的类型构造函数
【发布时间】:2020-10-07 21:35:51
【问题描述】:

考虑以下类型参数子句[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[_] &lt;: Int] 合法?

【问题讨论】:

  • 你可以这样做:type Test[A] = 3(或任何其他 Int,或 Int 本身) 然后你可以拨打h[Test]
  • 您可以将F[_ &lt;: A] &lt;: B 视为f: A =&gt; B 的类型级模拟。

标签: scala generics type-constraints higher-kinded-types type-constructor


【解决方案1】:

类型参数声明F[_] &lt;: Int意味着F的每个实例必须是Int的子类型。它在语法上是正确的,虽然很神秘:F 不必是Int 的子类型; F[_] 必须是Int 的子类型(适用于所有可能放在_ 中的类型)。这种F 的一个示例是始终返回Int

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

请注意,您可以在_ 中命名类型。例如。我可以声明一个类型参数F[X] &lt;: XX 是声明的局部变量,定义为出现在左侧的 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)

也许这让我们明白了界限应该是什么意思。

【讨论】:

    猜你喜欢
    • 2020-09-18
    • 2023-02-02
    • 1970-01-01
    • 1970-01-01
    • 2017-08-31
    • 2019-09-23
    • 1970-01-01
    • 2020-07-20
    • 1970-01-01
    相关资源
    最近更新 更多