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
From the scaladocs on Set, I think you just have to implement 4 or 5 methods. In this case I've decided to use a backing Seq[Thing] to create my actual set implementation.
class ThingSet(things: Seq[Thing]) extends Set[Thing] {
def contains(key: Thing) = { things.contains(key) }
def iterator: Iterator[Thing] = { things.iterator }
def +(elem: Thing) = new ThingSet(things :+ elem)
def -(elem: Thing) = new ThingSet(things.filterNot(_ == elem))
override def empty = new ThingSet(Nil)
}
class Thing(val name: String) {
def +(other: Thing) = { new ThingSet(List(this,other)) }
override def toString = name
}
val thing = new Thing("I'm a new thing")
println(thing + new Thing("I'm some other thing"))
results in:
Set(I'm a new thing, I'm some other thing)
note: I think you have to run this in a script file rather than the REPL because of the cyclical dependency between Thing and ThingSet.