Really struggling to figure out extending the immutable Set with a class that will represent a Set of concrete type. I\'m doing this to try and create a nice DSL.
I
Adapting from this Daily Scala post as well as the source to BitSet
, which is a wonderful example here because it is not a parameterized collection, and is rather short and simple.
import scala.collection.SetLike
import scala.collection.generic.{GenericSetTemplate, GenericCompanion, CanBuildFrom}
import scala.collection.mutable.{Builder, SetBuilder}
class ThingSet(seq : Thing*) extends Set[Thing]
with SetLike[Thing, ThingSet]
with Serializable {
override def empty: ThingSet = new ThingSet()
def + (elem: Thing) : ThingSet = if (seq contains elem) this
else new ThingSet(elem +: seq: _*)
def - (elem: Thing) : ThingSet = if (!(seq contains elem)) this
else new ThingSet(seq filterNot (elem ==): _*)
def contains (elem: Thing) : Boolean = seq exists (elem ==)
def iterator : Iterator[Thing] = seq.iterator
}
object ThingSet {
def empty: ThingSet = new ThingSet()
def newBuilder: Builder[Thing, ThingSet] = new SetBuilder[Thing, ThingSet](empty)
def apply(elems: Thing*): ThingSet = (empty /: elems) (_ + _)
def thingSetCanBuildFrom = new CanBuildFrom[ThingSet, Thing, ThingSet] {
def apply(from: ThingSet) = newBuilder
def apply() = newBuilder
}
}