advocateofnone
advocateofnone

Reputation: 2541

Why is the overriden val in constructor null?

In the following scenario

class A(name:String, job:String) 
{ 
   def profile = name + " " + job 
}

class B(name:String, job:String) 
{ 
  val a = new A(name,job)
  val b = a.profile
}

On initializing B and overriding val a

val b = new B("Sasha","Day dream") 
{ override val a = new A("John-Wick","Kill") }

I get a NullPointerException for val b = a.profile. My question is why is the overriden val null ? Is doing something like above, a bad practice ?

Upvotes: 1

Views: 72

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170919

This is a combination of several facts:

  1. a in val b = a.profile refers to the getter method, and it's the getter (and setter, for var) which gets overridden by override val a. So it returns the value of the field from the subclass.

  2. The subclass field is initialized in the subclass constructor.

  3. The B constructor runs before the subclass constructor, while the subclass field has its default value null.

A common fix is to switch vals to lazy val, so they are initialized on first use.

Upvotes: 5

Related Questions