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_A
andaSet_B
is allocated and set tonull
.A
is run.require
onaSet.contains(3)
is invokedaSet
is overridden inB
, it returnsaSet_B
.aSet_B
isnull
, an NPE is thrown.To avoid this, you can implement
aSet
as a lazy variable:This throws the
requirement failed
exception:Obligatory link to Scala's FAQ:
List of related questions: