I have a case class which takes two parameters of type A.
case class MyClass protected (lhs: A, rhs: A)
I would like to ensure the lhs is always <= than the rhs, so that when I pattern match
MyClass(lhs,rhs) I can rely on this fact.
I currently do this by enforcing the requirement in the companion object’s apply method, by swapping lhs and rhs if needed and then calling MyClass(lhsordered, rhsordered) since this factory way of building objects seems to be quite popular.
However, I’ve introduced a subclass of
MySubClass (bitem: B, rhs: A) extends MyClass(A(lhs), rhs). The bitem gets wrapped into a A object and then is passed to the superclass constructor. However, I can no longer enforce the construction requirement that lhs in
MyClass is <= rhs since
A(lhs) may be > than
Does this mean that all class building constraints should be held in the constructors?
If so, this means I cannot use case classes since the lhs and rhs that get passed into the object may be switched internally. So this means I’ll need to use normal classes, and this means I’ll have to build an
hash method and
unapply method? Is that correct?
Also can I have an
ensuring post condition at the end of a constructor?