输入 Scala 集合

发布于 2024-10-14 08:50:29 字数 950 浏览 9 评论 0原文

我想通过制作一个非常通用的前缀树来学习新的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

秋心╮凉 2024-10-21 08:50:29

好吧,问题是 MapLike 定义了一个 empty 返回 This,但是 Map.empty 返回 地图!

例如,尝试一下:

override def empty: PrefixMap[M,K,V] = new PrefixMap[M,K,V](None, (children: MapLike[K,PrefixMap[M,K,V],M[K,PrefixMap[M,K,V]]]).empty)

这将编译,因为您隐藏了 Map 的类型。该代码无法编译,因为它缺少抽象方法,但这是另一回事。

Well, the problem is that MapLike defines an empty that returns This, but Map.empty returns Map!

Try, for instance:

override def empty: PrefixMap[M,K,V] = new PrefixMap[M,K,V](None, (children: MapLike[K,PrefixMap[M,K,V],M[K,PrefixMap[M,K,V]]]).empty)

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文