The following code, when entered in REPL
abstract class A { val aSet: Set[Int]; require(aSet.contains(3)) }
class B extends A { val aSet = Set(4,5,6) }
new B()
gives a null point exception, rather than an invariant failure.
What would be the best idiom to solve this problem?
Similar questions:
Code Contracts: Invariants in abstract class
Private constructor in abstract class Scala?
and also online commentary: https://gist.github.com/jkpl/4932e8730c1810261381851b13dfd29d
When you declare a
val, several things happen:Your code
is roughly equivalent to
so, the following happens:
aSet_AandaSet_Bis allocated and set tonull.Ais run.requireonaSet.contains(3)is invokedaSetis overridden inB, it returnsaSet_B.aSet_Bisnull, an NPE is thrown.To avoid this, you can implement
aSetas a lazy variable:This throws the
requirement failedexception:Obligatory link to Scala's FAQ:
List of related questions: