Scala 的“This”和地图一样
假设我想用具体的实现 IntIntMap 来扩展 Scala 的 MapLike 特性。为此,我需要实现以下方法,
def get(key: A): Option[B]
def iterator: Iterator[(A, B)]
def + [B1 >: B](kv: (A, B1)): This
def -(key: A): This
This
类型是什么?我的重写方法签名应该是,
override def +=(kv: (Int, Int)): IntIntMap = {
// logic
}
还是只是 scala.reflect.This ?那么类的定义呢?应该是这样,
class IntIntMap(...) extends MapLike[Int,Int,This] { ... }
还是完全是别的什么?
Say I wanted to extend Scala's MapLike trait with a concrete implementation, IntIntMap. In order to do so, I need to implement the following methods,
def get(key: A): Option[B]
def iterator: Iterator[(A, B)]
def + [B1 >: B](kv: (A, B1)): This
def -(key: A): This
What is the This
type? Should my overriding method signature be,
override def +=(kv: (Int, Int)): IntIntMap = {
// logic
}
Or just scala.reflect.This
? What about the class definition? Should it be,
class IntIntMap(...) extends MapLike[Int,Int,This] { ... }
or something else entirely?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该扩展
MapLike[Int, Int, IntIntMap]
,并且This
变为IntIntMap
。You should extend
MapLike[Int, Int, IntIntMap]
, andThis
becomesIntIntMap
.您应该首先查看 Scala 集合的架构< /a>.它向您展示如何整合您自己的收藏。
但是,在示例中实现
+
方法会遇到一些麻烦,因为它应该允许添加与 Int 超类型匹配的值并返回适当的Map
。由于This
应该是Map[Int,Int]
你会遇到麻烦。我宁愿建议在某处有一个类型定义:
并最终使用隐式来引入特定的方法。
You should have a look first at The Architecture of Scala Collections. It shows you how to integrate you own collections.
However, you will have some trouble implementing the
+
method in you example, because it should allow to add values matching a supertype of Int and returning an appropriateMap
. SinceThis
should be aMap[Int,Int]
you will run into trouble.I would rather recommend to just have a type definition somewhere:
and eventually use implicits to bring specific methods.
不是保留字,不是某个类的名称,而是 MapLike 中的第三个类型参数。
类型声明为
MapLike[K, +V, +This <: MapLike[K, V, This]
。它可以被称为任何其他方式。大多数时候,This 应该是实际的实现类,因此得名。在您的情况下,如果没有该参数,
+
结果类型将被声明为 MapLike,而不是 IntIntMap。在+
上,这不会是问题,因为您必须定义它,并且这样做您可以更改结果类型。但是不需要重新定义并且使用+
实现的方法(例如++
仍然会返回 MapLike.Not a reserved word, not the name of some class, but the third type parameter in MapLike.
Type declaration is
MapLike[K, +V, +This <: MapLike[K, V, This]
. It could be called any other way. Most of the time, the This should be the actual implementor class, hence the name. in your caseWithout that parameter,
+
result type would have be declared MapLike, not IntIntMap. On+
, that would not be a problem, because you have to define it, and doing that you can change the result type. But methods that you don't need to redefine and which are implemented using+
(such as the++
would still return MapLike.