I found an error in my scala code, which puzzles me. Below is a simplified version of the problem.
In the constructor of an abstract class, I want to check a few asserts about the abstract methods. Thus when an object of a subclass is made, these asserts are checked, to see if all is implemented as it should.
It goes wrong when the subclass implements an abstract method using a "val" however:
Scala code:
abstract class A {
def aval : String
assert(aval != null, "aval == null")
assert(aval == "B", "aval: "+aval)
}
class B extends A {
def aval = "B"
}
class C extends A {
val aval = "B"
}
object VariousScalaTests {
def main(args : Array[String]) : Unit = {
val b = new B
val c = new C
}
}
Scala Error:
Exception in thread "main" java.lang.AssertionError: assertion failed: aval == null
at scala.Predef$.assert(Predef.scala:92)
at A.<init>(VariousScalaTests.scala:4)
at C.<init>(VariousScalaTests.scala:12)
at VariousScalaTests$.main(VariousScalaTests.scala:19)
at VariousScalaTests.main(VariousScalaTests.scala)
So it fails at the last line of code: "val c = new C". Class B works perfectly, but class C doesn't! The only difference is that C implements aval using "val" and B using "def".
So my question, most of all, why this difference? I don't understand what's going on.
And is there a way to make it work as I want in both cases in scala? Or am I just missing a more elegant way to assert what I want in scala?