输入 Scala 集合
我想通过制作一个非常通用的前缀树来学习新的 Scala 集合框架。不仅键和值必须是参数,而且每个节点中使用的映射的类型也必须是参数。所以我尝试了这个:
import collection.immutable.MapLike
class PrefixMap[+M[K1,+V1] <: Map[K1,V1] with MapLike[K1,V1,M[K1,V1]],K,+V](val content: Option[V], val children: M[K,PrefixMap[M,K,V]])
extends Map[Iterable[K],V]
with MapLike[Iterable[K],V,PrefixMap[M,K,V]] {
override def empty: PrefixMap[M,K,V] = new PrefixMap[M,K,V](None, children.empty)
}
但这不能编译:
PrefixMap.scala:19: error: type mismatch;
found : scala.collection.immutable.Map[K,PrefixMap[M,K,V]]
required: M[K,PrefixMap[M,K,V]]
override def empty: PrefixMap[M,K,V] = new PrefixMap[M,K,V](None, children.empty)
^
one error found
这让我很困惑。我可以从文档中看到 MapLike 有一个返回“This”的空值。因此,由于 Children 的类型为 M[K,PrefixMap[M,K,V]],children.empty 也应该是该类型。
出了什么问题,可以修复吗?
I wanted to learn the new Scala collections framework by making a very general prefix tree. Not only must the keys and the values be parameters, but the type of the maps used in each node must be parameters too. So I tried this:
import collection.immutable.MapLike
class PrefixMap[+M[K1,+V1] <: Map[K1,V1] with MapLike[K1,V1,M[K1,V1]],K,+V](val content: Option[V], val children: M[K,PrefixMap[M,K,V]])
extends Map[Iterable[K],V]
with MapLike[Iterable[K],V,PrefixMap[M,K,V]] {
override def empty: PrefixMap[M,K,V] = new PrefixMap[M,K,V](None, children.empty)
}
But this doesn't compile:
PrefixMap.scala:19: error: type mismatch;
found : scala.collection.immutable.Map[K,PrefixMap[M,K,V]]
required: M[K,PrefixMap[M,K,V]]
override def empty: PrefixMap[M,K,V] = new PrefixMap[M,K,V](None, children.empty)
^
one error found
This confuses me. I can see from the documentation that a MapLike has an empty that returns "This". So, since children is of type M[K,PrefixMap[M,K,V]], children.empty should be of that type too.
What's going wrong, and can it be mended?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,问题是
MapLike
定义了一个empty
返回This
,但是Map.empty
返回地图!
例如,尝试一下:
这将编译,因为您隐藏了 Map 的类型。该代码无法编译,因为它缺少抽象方法,但这是另一回事。
Well, the problem is that
MapLike
defines anempty
that returnsThis
, butMap.empty
returnsMap
!Try, for instance:
This will compile, because you are hiding
Map
's type. The code won't compile because it is missing abstract methods, but that's another matter.