Identity Set anyone?

Does anyone have an implementation of an IdentitySet, possibly derived from a LinkedHashSet? I found a good looking version of an IdentityHashMap at and suspect there can be a similar Set with methods like elemEquals, elemHashCode, and maybe IdentityHashSet overridden. It seems like the class would be described as

class IdentityHashSet[A <: AnyRef]() extends LinkedHashSet[A] with GenericSetTemplate[A, IdentityHashSet]
    with SetLike[A, IdentityHashSet[A]] with HashTable[A, IdentityHashSet.Entry[A]] {

but that GenericSetTemplate[A, IdentityHashSet] isn’t quite normal in that IdentityHashSet would seem to require an A or something.

Versions without it will compile, but I wouldn’t know to what extent they don’t do everything required.
I do not want to wrap every value in a wrapper that has redefined equals. This is for Scala 2.12 and 2.11. Maybe the newer version have something already.

How about something like ? A set built on the java IdentityHashMap.

Thanks for the suggestion. My present implementation is much like the one you suggest, but the problem is that it doesn’t play nicely enough with other Scala collection operations. I’m trying to get better integration.

Have you tried using scala.jdk.CollectionConverters (or JavaConverters in older Scala versions)? This approach of wrapping Java collections but getting Scala friendly APIs has worked well for me in the past.

That’s a great idea! I’m going to look into it.

The the time being I’m trying this out:

import scala.collection.JavaConverters._
import scala.collection.mutable

object IdentityHashSet {
  type IdentityHashSet[T <: AnyRef] = mutable.Set[T]

  def apply[T <: AnyRef](): IdentityHashSet[T] = {
    val jMap = new java.util.IdentityHashMap[T, java.lang.Boolean]
    val jSet = java.util.Collections.newSetFromMap[T](jMap)
    val sSet = jSet.asScala