实现HashSet

时间:2014-07-31 08:21:22

标签: scala

我的哈希集实现中有一些奇怪的编译错误。这段代码

class HashSet[A] extends scala.collection.mutable.Set[A] {
  override def +=(elem: A): HashSet[A] = {
    /* doing stuff */
    this
  }
}

产生以下错误

Error:(15, 16) overriding method += in trait SetLike of type (elem: A)HashSet.this.type;
 method += has incompatible type
  override def +=(elem: A): HashSet[A] = {
               ^
Error:(15, 16) overriding method += in trait Builder of type (elem: A)HashSet.this.type;
 method += has incompatible type
  override def +=(elem: A): HashSet[A] = {
               ^
Error:(15, 16) overriding method += in trait Growable of type (elem: A)HashSet.this.type;
 method += has incompatible type
  override def +=(elem: A): HashSet[A] = {
               ^

我该如何修复它们?

1 个答案:

答案 0 :(得分:1)

您要覆盖的方法是HashSet.+=,其定义如下:

def +=(elem: A): HashSet.this.type

返回类型为HashSet.this.type。您使用返回不同类型HashSet[A]的方法覆盖它。这是不允许的。

换句话说:改变一个可变集合不应该只返回相同类型的任何集合,它应该返回完全相同的集合(即this )。您正确地在方法中返回this,但是您可以使返回类型更精确,以明确声明您不仅仅是返回任何 HashSet,而是返回 HashSet

class HashSet[A] extends scala.collection.mutable.Set[A] {
  override def +=(elem: A):       this.type   = ???
  override def iterator:          Iterator[A] = ???
  override def -=(elem: A):       this.type   = ???
  override def contains(elem: A): Boolean     = ???
}

由于您要覆盖返回类型为this.type的方法,因此只需让Scala推断返回类型也会有效:

class HashSet[A] extends scala.collection.mutable.Set[A] {
  override def +=(elem: A)                    = ???
  override def iterator                       = ???
  override def -=(elem: A)                    = ???
  override def contains(elem: A)              = ???
}