好的,所以我有这个非常简单的设置:
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
方法来推断类型?
答案 0 :(得分:3)
以下&#34;冗余&#34;似乎满足了编译器:
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]
,其中Elem
在S
中是不变的。
或者我错过了关键的一点?