通常有效的方法是将单例类型作为类型参数传播到EnrichGraph
. 这意味着一些额外的样板,因为您必须将implicit class
aclass
和 an拆分为implicit def
.
class EnrichGraph[G <: Graph](val G: G) extends AnyVal {
def roots: Iterable[G#NodeT] = G.nodes.filter(!_.hasPredecessors)
//...
}
implicit def EnrichGraph(g: Graph): EnrichGraph[g.type] = new EnrichGraph[g.type](g)
这里的要点是G#NodeT =:= H.NodeT
如果G =:= H.type
,或者换句话说(H.type)#NodeT =:= H.NodeT
。(=:=
是类型相等运算符)
你得到那个奇怪类型的原因是它roots
有一个依赖于路径类型的类型。并且该路径包含 value G
。因此val roots2
,您的程序中的类型需要包含 G
. 但是由于G
绑定到一个没有被任何变量引用的实例EnrichGraph
,编译器无法构造这样的路径。编译器可以做的“最好”的事情是构造一个类型,其中省略了路径的那部分:Set[_1.G.NodeT] forSome { val _1: EnrichGraph }
. 这是我实际使用您的代码得到的类型;我假设您正在使用以不同方式打印此类型的 Intellij。
正如@DmytroMitin 所指出的,一个可能更适合您的版本是:
import scala.collection.mutable.Set
class EnrichGraph[G <: Graph](val G: G) extends AnyVal {
def roots: Set[G.NodeT] = G.nodes.filter(!_.hasPredecessors)
//...
}
implicit def EnrichGraph(g: Graph): EnrichGraph[g.type] = new EnrichGraph[g.type](g)
由于您的其余代码实际上需要 aSet
而不是Iterable
.
The reason why this still works despite reintroducing the path dependent type is quite tricky. Actually now roots2
will receive the type Set[_1.G.NodeT] forSome { val _1: EnrichGraph[H.type] }
which looks pretty complex. But the important part is that this type still contains the knowledge that the G
in _1.G.NodeT
has type H.type
because that information is stored in val _1: EnrichGraph[H.type]
.
With Set
you can't use G#NodeT
to give you the simpler type signatures, because G.NodeT
is a subtype of G#NodeT
and Set
is unfortunately invariant. In our usage those type will actually always be equivalent (as I explained above), but the compiler cannot know that.