Assuming defintion:
case class IntegerWrapper(i : Int)
and being in a situation that potentially large amounts of IntegerWrapper instances with i=[0..N> may be created what does one have to do to:
-
Map this range to a fixed set of singletons
[IntegerWrapper(0) .. IntegerWrapper(N)> -
Preserve existing value semantics for class
IntegerWrapper(matching, equals, hashcode, serialization)
I am looking to do instance sharing akin to what java.lang.Integer does. I guess my question is if this can be done without having to do everything myself. Simply defining a companion object with an apply(i : Int) does not compile. Any suggestions?
Something like this?
The advantage is that
equalsandhashCodeare still generated by the compiler, sinceIntegerWrapperImplis a case class. The disadvantage is that you cannot directly use other compiler-added case class goodies, e.g.,copy. If you want to use that, either exposeIntegerWrapperImplto the client, or, IMHO better, addcopyto theIntegerWrapperinterface.Pattern matching works as usual: