scala中具有自递归类型的对象集合
Collection of object with self recursive type in scala
trait Node[N<:Node[N]] { self:N =>
}
trait A extends Node[A]
trait B {
def list:List[Node[_]]
def as:List[A] = list.collect { case x:A => x }
}
我在集合中使用自递归类型时遇到了一些问题。在此示例中,编译器给出错误
def as = list.collect { case x:A => x }
^
type arguments [_] do not conform to trait Node's type parameter bounds [N <: Node[N]]
因为List[Node[_]]中的通配符不符合类型绑定。是否有任何正确的方法可以将通配符类型指定为递归绑定?
一种解决方法是
def as = {
list match {
case list:List[Node[n]] => list.collect { case x:A => x }
}
}
这很丑。
这似乎有效:
trait B {
def list: List[_ <: Node[_]]
def as:List[A] = list.collect { case x:A => x }
}
你可以用存在主义来解决这个问题
trait Node[N<:Node[N]] { self:N =>
}
trait A extends Node[A]
trait B {
def list:List[X forSome {type X <: Node[X]}]
def as:List[A] = list.collect { case x:A => x }
}
只是一个公平的警告 forSome
将在某个时候从 scala 中删除。你能告诉我们更多关于你想做什么的事情吗?也许有更优雅的方法来做到这一点
trait Node[N<:Node[N]] { self:N =>
}
trait A extends Node[A]
trait B {
def list:List[Node[_]]
def as:List[A] = list.collect { case x:A => x }
}
我在集合中使用自递归类型时遇到了一些问题。在此示例中,编译器给出错误
def as = list.collect { case x:A => x }
^
type arguments [_] do not conform to trait Node's type parameter bounds [N <: Node[N]]
因为List[Node[_]]中的通配符不符合类型绑定。是否有任何正确的方法可以将通配符类型指定为递归绑定? 一种解决方法是
def as = {
list match {
case list:List[Node[n]] => list.collect { case x:A => x }
}
}
这很丑。
这似乎有效:
trait B {
def list: List[_ <: Node[_]]
def as:List[A] = list.collect { case x:A => x }
}
你可以用存在主义来解决这个问题
trait Node[N<:Node[N]] { self:N =>
}
trait A extends Node[A]
trait B {
def list:List[X forSome {type X <: Node[X]}]
def as:List[A] = list.collect { case x:A => x }
}
只是一个公平的警告 forSome
将在某个时候从 scala 中删除。你能告诉我们更多关于你想做什么的事情吗?也许有更优雅的方法来做到这一点