Reputation: 2541
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
Reputation: 170919
This is a combination of several facts:
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.
The subclass field is initialized in the subclass constructor.
The B
constructor runs before the subclass constructor, while the subclass field has its default value null
.
A common fix is to switch val
s to lazy val
, so they are initialized on first use.
Upvotes: 5