Can I create a collection in Scala that uses different equals/hashCode/compare implementations?

二次信任 提交于 2019-12-05 12:09:37
Ben Lings

This is a similar question. The accepted answer in that case was to use a TreeSet and provide a custom Comparator.

Depending on your needs you could create a box for which you use identity checks on the contained element such as:

class IdentBox[T <: AnyRef](val value: T) {

    override def equals(other: Any): Boolean = other match {
      case that: IdentBox[T] => that.value eq this.value
      case _ => false
    }

    override def hashCode(): Int = value.hashCode

  }

And make the collection to contain those boxes instead of the elements directly: Set[IdentBox[T]]

It has some overhead of boxing / unboxing but it might be tolerable in your use case.

Since you don't require a reference to the "seen" objects, but just a boolean value for "contains", I would suggest just using a mutable.Set[Int] and loading it with values obtained by calling System.identityHashCode(obj).

Scala custom collections have enough conceptual surface area to scare off most people who want a quick tweak like this.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!