3

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

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方法来推断类型?

4

1 回答 1

3

以下“冗余”似乎满足编译器:

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

也就是说,添加with Elem[S]. 看起来 Scala 编译器的一个不必要的缺陷是不能S从.E1 <: Elem[S]ElemS

还是我错过了关键的一点?

于 2014-04-24T17:45:12.787 回答