NullPointerException on accessing val override in abstract constructor

Consider the following (simplified) example:

abstract class Bar[T] {
    val f: PartialFunction[T, T]
    val default: PartialFunction[T, T] = { case x => x }
    val chained = f orElse default
}

class Foo extends Bar[Int] {
    val f: PartialFunction[Int, Int] = { case 1 => 2 }
}

And watch it crash:

scala> val foo = new Foo
java.lang.NullPointerException
        at Bar.<init>(<console>:8)
        at Foo.<init>(<console>:6)
        at .<init>(<console>:7)
        at .<clinit>(<console>)
        at RequestResult$.<init>(<console>:9)
        at RequestResult$.<clinit>(<console>)
        at RequestResult$scala_repl_result(<console>)
        ....

However, if we put chainedin a specific class:

abstract class Bar[T] {
    val f: PartialFunction[T, T]
    val default: PartialFunction[T, T] = { case x => x }
}

class Foo extends Bar[Int] {
    val f: PartialFunction[Int, Int] = { case 1 => 2 }
    val chained = f orElse default
}

It works as expected:

scala> val foo = new Foo
foo: Foo = Foo@16132c4

I must admit that I absolutely do not know what is happening here. Error? (This is on Scala 2.8.1.)

+5
source share
2 answers

"Why is my abstract or redefined shaft null?" https://github.com/paulp/scala-faq/wiki/Initialization-Order

+5
source

: , . , f Bar. "" Bar Foo - sans f! - Bar. f chained.

.

0

All Articles