Scala:方便绑定集合类型参数
为了方便、清晰和抽象,我想为参数化集合特征的特定绑定指定另一个名称。例如,首先考虑:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用类型别名:
请注意,这不会为您提供
object MyMap
,并且如果您定义了它,它不是伴随对象(object Map
> 是)并且编译器不会检查它的隐式转换。Use a type alias:
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.@阿列克谢·罗曼诺夫
类型别名不会为您提供工厂方法。另一方面,进口会。
@Alexey Romanov
A type alias won't give you the factory method. An import on the other hand will.