循环类型参数定义在Scala中 [英] Circular type parameters definition in scala
问题描述
我试图定义一个通用容器,其元素可以返回封闭的容器。例如:
I am trying to define a generic container whose elements can return the enclosing container. Something like:
abstract class Container[E <: Element] { // compile error
def contains( e: E ): Boolean
def addNewElement(): Unit
}
abstract class Element[C <: Container] { // compile error
def enclosingContainer(): C
}
class MyContainer extends Container[MyElement] {
private var elements = List[MyElement]()
override def contains( elem: MyElement ) = elements.contains( elem )
override def addNewElement() { elements ::= new MyElement(this) }
}
class MyElement( container: MyContainer ) extends Element[MyContainer] {
override val enclosingContainer = container
}
然而,没有编译,因为我应该在抽象类Container [E<:Element]
定义中为元素
提供一个类型参数以及抽象类元素中的
定义。 Container
类型元素[C<:Container]
However that snippet does not compile because I should give a type parameter to Element
in the abstract class Container[E <: Element]
definition and a type to Container
in the abstract class Element[C <: Container]
definition.
我有一种方法可以实现我所寻找的行为吗?对于 Container
和 Element
是否有适当的声明?我应该定义第三方对象吗?
I there a way to achieve the behavior I am looking for ? Is there an appropriate declaration for Container
and Element
? Should I define a third-party object ?
推荐答案
其他解决方案未能强制实施类型匹配:给定类型 ContainerImpl extends Container
,您应该确保 ContainerImpl.EC
应该是 ContainerImpl
而不是其他容器。这是一个强制执行此操作(改编自 http://programming-scala.labs.oreilly .com / ch13.html ):
The other solutions already given fail to enforce that the types match: that is, given a type ContainerImpl extends Container
, you should be sure that ContainerImpl.E.C
should be ContainerImpl
and not some other container. Here is one which does enforce this (adapted from http://programming-scala.labs.oreilly.com/ch13.html):
abstract class ContainerWithElement {
type C <: Container
type E <: Element
trait Container {
self: C =>
def contains( e: E ): Boolean
def addNewElement(): Unit
}
trait Element {
self: E =>
def enclosingContainer(): C
}
}
这篇关于循环类型参数定义在Scala中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!