scala - 修复更高种类类型的类型推断

好的,所以我有这个非常简单的设置:

trait Sys[S <: Sys[S]]

trait Elem[S <: Sys[S]]

trait AttrElem[S <: Sys[S]] {
  type E <: Elem[S]

  def attributes: Any
  def element: E
}

还有一个工厂:

object Factory {
  def apply[S <: Sys[S], E1 <: Elem[S]](
    elem: E1): AttrElem[S] { type E = E1 } = new Impl(elem)

  private class Impl[S <: Sys[S], E1 <: Elem[S]](val element: E1) 
    extends AttrElem[S] { 

    type E = E1

    def attributes = 1234
  }
}

现在在实践中 f*** Scala 类型推断崩溃了:

def test[S <: Sys[S]](elem: Elem[S]): Unit = {
  Factory(elem)
}

<console>:62: error: inferred type arguments [Nothing,Elem[S]] do not conform
  to method apply's type parameter bounds [S <: Sys[S],E1 <: Elem[S]]
             Factory(elem)
             ^

所以我的下一个尝试是存在类型:

object Factory {
  def apply[S <: Sys[S], E1[~] <: Elem[~] forSome { type ~ <: Sys[~] }](
    elem: E1[S]): AttrElem[S] { type E = E1[S] } = new Impl(elem)

  private class Impl[S <: Sys[S], E1[~] <: Elem[~] forSome { type ~ <: Sys[~] }](
    val element: E1[S]) extends AttrElem[S] { 

    type E = E1[S]

    def attributes = 1234
  }
}

这给了我以下可爱的信息:

<console>:62: error: inferred kinds of the type arguments (S,E1[S]) do not 
  conform to the expected kinds of the type parameters (type S,type E1) in
  class Impl.
E1[S]'s type parameters do not match type E1's expected parameters:
type E1 has one type parameter, but type E1 (in class Impl) has one
               elem: E1[S]): AttrElem[S] { type E = E1[S] } = new Impl(elem)
                                                              ^

“类型 E1 有一个类型参数,但类型 E1 有一个”——嗯?


问题:如何定义工厂的apply方法来推断类型?

最佳答案

下面的“冗余”似乎让编译器满意:

def apply[S <: Sys[S], E1 <: Elem[S]](elem: E1 with Elem[S]): 
  AttrElem[S] { type E = E1 } = ...

也就是加入with Elem[S] .不推断 S 似乎是 Scala 编译器不必要的缺陷来自 E1 <: Elem[S]其中 ElemS 中不变.

还是我漏掉了一个关键点?

https://stackoverflow.com/questions/23275767/

相关文章:

angularjs - 关于Angular $q defer对象的问题

shell - 将所有第二层 mp3 递归转换为第三层并更新 ID3

angularjs - ng-grid cellTemplate 问题与单元格的背景颜色

datomic - 将任意键/值条目与数据实体一起存储

ruby-on-rails - 无法使用 CanCan 从 rails_admin 管理模型

dart - 如何在 Dart 中产生一个新的隔离?

types - InnoSetup : custom setup type - display me

clojure - 是否可以检索定义变量的条件图?

build - 不安全代码需要指定 `unsafe` 命令行选项 Monodevelop 4.0.1

maven - java.lang.IllegalStateException : Could no