【问题标题】:Can't use a type projection to a recursive (f-bounded) type不能将类型投影用于递归(f 有界)类型
【发布时间】:2014-07-07 20:45:09
【问题描述】:

在使用从一种 f 有界类型到另一种类型的投影时,我遇到了一个我不理解的类型错误。可能是related to an earlier question,但我不确定。

设置很简单:

trait Foo[F <: Foo[F]] {
  type I <: Foo[I]
}

也就是说,我有一个系统F,其中包含到另一个类似系统的投影。

好的,现在我需要做的是,给定F,能够使用F#I。但是编译器抱怨:

trait Test {
  def apply[F <: Foo[F]]: Unit = bar[F#I]   // type error
  def bar  [F <: Foo[F]]: Unit = ???
}

<console>:52: error: type arguments [F#I] do not conform to method bar's 
  type parameter bounds [F <: Foo[F]]
             def apply[F <: Foo[F]]: Unit = bar[F#I]
                                               ^

那为什么会这样呢?有没有解决办法?


实际上,它似乎是this problem 的变体,无法解释发生了什么。


编辑:例如以下编译:

trait Test {
  def apply[F <: Foo[F] { type I = I1 }, I1 <: Foo[I1]]: Unit = bar[I1]
  def bar  [F <: Foo[F]]: Unit = ???
}

现在的问题是,那个糟糕的类型参数I1 会在我的 API 中冒出几十个级别,所以我真的需要找到一个避免第二个类型参数的解决方案。

【问题讨论】:

    标签: scala type-projection bounded-quantification


    【解决方案1】:

    好的,所以我检查了我现有的代码库,直到我发现以前使用过这个解决方法:

    trait Foo[F <: Foo[F]] {
      type I  <: Foo[I]
      type Tx <: Txn[F]
    }
    
    trait Txn[F <: Foo[F]] {
      val foo: F
    }
    
    trait Test {
      def apply[F <: Foo[F]](implicit tx: F#Tx): Unit = {
        val foo: F = tx.foo
        bar[F, foo.I](tx)
      }
    
      def bar[F <: Foo[F], I <: Foo[I]](implicit tx: F#Tx): Unit = ???
    }
    

    也就是说,我需要有一个,从中我得到一个依赖路径的类型,然后打字机又高兴了。

    我仍然很想了解为什么我的原始代码被拒绝。

    【讨论】:

      猜你喜欢
      • 2021-06-25
      • 1970-01-01
      • 1970-01-01
      • 2019-11-18
      • 1970-01-01
      • 1970-01-01
      • 2018-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多