I've seen some blogs on the Pimp my Library pattern
, and these seem to work well for adding behavior to classes.
But what if I have a case class
and I want to add data members
to it? As a case class I can't extend it (inheriting from a case class is deprecated/strongly discouraged). Will any of these pimp patterns allow me to add data to a case class?
This is not the way to do. Just a proof of possibility. With this way you can get plenty of problems.
WeakHashMap: A hash map with references to entries which are weakly reachable. Entries are removed from this map when the key is no longer (strongly) referenced. This class wraps java.util.WeakHashMap.
Note that due to
case class
's overriddenequals
method you get this funny behavior:so you should not use
case class
or use it withoverride def equals(that: Any) = this eq that.asInstanceOf[AnyRef]
.No - I don't see how you could make this work because the enriched instance is usually thrown away (note: newly the pimp-my-library pattern is called enrich-my-library). For example:
You would have to make sure you kept hold of the wrapped instance:
However, I find this not useful in practice. You have a wrapper; you're better off making this explicit