Scala:方便绑定集合类型参数

发布于 2024-12-04 22:31:54 字数 743 浏览 0 评论 0原文

为了方便、清晰和抽象,我想为参数化集合特征的特定绑定指定另一个名称。例如,首先考虑:

import collection.mutable.Map // NB: Map is a trait
val m1 = Map[String, Int]()   // uses the Map companion object to create a HashMap

现在我想用 MyMap 替换 Map[String, Int]。理想情况下,我只想做类似的事情:

trait MyMap extends Map[String, Int]
object MyMap extends Map[String, Int]   // not good enough by itself, need some apply defs
val m2 = MyMap()                        // nope

我可以向 MyMap 伴随对象添加更多内容,或者我可以使 MyMap 扩展 HashMap[String, Int] 并忘记依赖于 Map 伴随对象内部的默认魔法。

但这些替代方案对于应该很简单的事情来说似乎太多了:我只想 MyMap 无论出现在哪里,都可以像 Map[String, Int] 一样工作。最简单的方法是什么,还是我错过了一些更深层次的原则?

For convenience, clarity, and abstraction, I want to make up another name for a specific binding of a parameterized collection trait. For instance, first consider:

import collection.mutable.Map // NB: Map is a trait
val m1 = Map[String, Int]()   // uses the Map companion object to create a HashMap

Now I want to substitute MyMap for Map[String, Int]. Ideally I would just like to do something like:

trait MyMap extends Map[String, Int]
object MyMap extends Map[String, Int]   // not good enough by itself, need some apply defs
val m2 = MyMap()                        // nope

I could add more stuff to the MyMap companion object, or I could make MyMap extend HashMap[String, Int] and forget about relying on the magic defaulting inside the Map companion object.

But those alternatives seem like too much work for something that should be simple: I just want MyMap to act like Map[String, Int] wherever it appears. What's the easiest way to do that, or am I missing some deeper principle?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

无所谓啦 2024-12-11 22:31:54

使用类型别名:

type MyMap = Map[String, Int]

请注意,这不会为您提供object MyMap,并且如果您定义了它,它不是伴随对象(object Map > 是)并且编译器不会检查它的隐式转换。

Use a type alias:

type MyMap = Map[String, Int]

Note this won't give you object MyMap, and if you define it, it is not the companion object (object Map is) and the compiler won't check it for implicit conversions.

£烟消云散 2024-12-11 22:31:54

@阿列克谢·罗曼诺夫
类型别名不会为您提供工厂方法。另一方面,进口会。

scala> import collection.mutable.{Map => MyMap}
scala> val m1 = MyMap()
m1: scala.collection.mutable.Map[Nothing, Nothing] = Map()

@Alexey Romanov
A type alias won't give you the factory method. An import on the other hand will.

scala> import collection.mutable.{Map => MyMap}
scala> val m1 = MyMap()
m1: scala.collection.mutable.Map[Nothing, Nothing] = Map()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文