This page is no longer maintained — Please continue to the home page at www.scala-lang.org

Instance variable initialization

No replies
richard emberson
Joined: 2010-03-22,
User offline. Last seen 42 years 45 weeks ago.

I have a base class and derived class.
In the base class' constructor a magic utility
is called which sets the values the derived class'
instance variables.
Then the derived class' constructor is executed.

class BassClass {
// sets derived class' someString instance variable
MagicUtility.onInstantiation(this)
}

class DerivedClass extends BaseClass {
private var someString: String = null
or
private var someString: String = _
}

Now, if I declare the derived class instance variable as:
private var someString: String = null

Then the value set by the MagicUtility is overwritten
and the value is null.

But, if I declare it as:
private var someString: String = _

it is not overwritten; the value set while in the base class
constructor is there after the derived class constructor ends.

I was rather surprised by this (Happy, that using '_' was a
solution, but still surprised).

What are the semantics, side effects, and usages for declaring
an instance variable as equal to '_'?

Is it the case that:
private var someString: String = _

declares the instance variable, while:
private var someString: String = null

both declares it and sets its value?

Richard

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland