I found an error in my scala code that puzzled me. The following is a simplified version of the problem.
In the constructor of an abstract class, I want to check out a few statements about abstract methods. Thus, when a subclass object is created, these statements are checked to ensure that everything is implemented as it should.
It is incorrect if a subclass implements an abstract method using "val":
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)
Thus, it does not work in the last line of code: "val c = new C". Class B works fine, but class C doesn't work! The only difference is that C implements aval using "val" and B using "def".
, , , ? , .
, , scala? , scala?