【问题标题】:Covariance and higher-kinded types in Scala 2.12Scala 2.12 中的协方差和更高种类的类型
【发布时间】:2017-10-26 13:05:09
【问题描述】:

以下代码

type Id[+A] = A
type ReprF[A, F[_]] = Unit
type Repr[A] = ReprF[A, Id]

在 Scala 2.12 中无法编译,出现错误

covariant type Id occurs in invariant position in type 
[A]Playground.this.ReprF[A,Playground.this.Id] of type Repr

我不明白为什么Id 的协方差会阻止这段代码编译。

ReprF 不应该关心F 是否是协变的,它只需要一种类型的* -> *

我错过了什么吗?

奇怪的是它在 Scala 2.11 中可以正确编译。

这是scastie snippet,如果您想尝试一下代码。任何帮助将不胜感激!

【问题讨论】:

    标签: scala covariance higher-kinded-types type-alias


    【解决方案1】:

    我认为编译器对协变 ID 感到非常困惑。即使所有都是协变的,它仍然会给出相同的错误:

    trait Test {
      type Id[+A] = A
      type ReprF[+A, +F[+_]] = Unit
      type Repr[+A] = ReprF[A, Id]
    }
    
    Error: covariant type Id occurs in invariant position in type [+A]Test.this.ReprF[A,Test.this.Id] of type Repr
      type Repr[+A] = ReprF[A, Id]
    

    如果我不定义 ID,那很好:

    trait Test {
      type Id[+A]
      type ReprF[A, F[_]] = Unit
      type Repr[A] = ReprF[A, Id]
    }
    

    【讨论】:

    • 是的,这个例子是从像你第一个 sn-p 这样的代码中提取的。非常有趣和令人费解的是你在第二个中发现了什么!
    猜你喜欢
    • 2018-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多