In a previous SO post I asked about an idiomatic way to make a container class wrapping an immutable collection thread-safe. Answers that I received all involved using various flavors of read/write locks or synchronization which is not what I wanted.
Let me ask a different question. How do I make the following class that wraps an immutable container immutable? The methods add
/remove
need to return a new MyContainer
class instance suitably altered, but I can't quite see how to do it...
class MyContainer[A] {
// method that returns a new MyContainer that includes the additional thing...
def add(thing: A): MyContainer[A] = {
???
}
def filter(p: A => Boolean): Option[Iterable[A]] = {
val filteredThings = backingStore.values.filter(p)
if (filteredThings.isEmpty) None else Some(filteredThings)
}
// method that returns a new MyContainer that does not include the thing with given uuid
def remove(uuid: UUID): MyContainer[A] = {
???
}
@ volatile private[this] var backingStore = immutable.HashMap.empty[UUID, A]
}
Thoughts?
EDIT: In response to comment, one possible solution would be something similar to the following...
class MyContainer[A](val backingStore: immutable.HashMap[UUID, A]) {
def add(thing: A): MyContainer[A] = {
new MyContainer(backingStore + (thing.uuid -> thing))
}
def filter(p: A => Boolean): Option[Iterable[A]] = {
val filteredThings = backingStore.values.filter(p)
if (filteredThings.isEmpty) None else Some(filteredThings)
}
def remove(uuid: UUID): MyContainer[A] = {
new MyContainer(backingStore - uuid)
}
}
...backingStore
is no longer private (but could put private
in constructor). More thoughts?