Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullPointerException when accessing overriden val in abstract constructor

Tags:

scala

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 chained in the concrete 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 have to admit I have absolutely no idea what is happening here. Bug? (This is on Scala 2.8.1.)

like image 318
Knut Arne Vedaa Avatar asked Jan 15 '11 19:01

Knut Arne Vedaa


1 Answers

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

like image 99
retronym Avatar answered Nov 15 '22 03:11

retronym