I\'m writing a type-safe code and want to replace apply() generated for case classes with my own implementation. Here it is:
import shap
There is a solution that is usually used if you want to provide some smart constructor and the default one would break your invariants. To make sure that only you can create the instance you should:
applynew.copyThis is achieved by this interesing patten:
sealed abstract case class MyCaseClass private (value: String)
object MyCaseClass {
def apply(value: String) = {
// checking invariants and stuff
new MyCaseClass(value) {}
}
}
Here:
abstract prevents generation of .copy and applysealed prevents extending this class (final wouldn't allow abstract)private constructor prevents using newWhile it doesn't look pretty it's pretty much bullet proof.
As @LuisMiguelMejíaSuárez pointed out this is not necessary in your exact case, but in general that could be used to deal with edge cases of case class with a smart constructor.