Take the 2-minute tour ×

I know there are multiple questions addressing related problems, but I'm not sure it does attack exactly what I'm looking for. I'm still new to Scala, after several years of Java development. I'm looking for the best way to test if an object has been initialized, and if not, initialize it then. For example, in Java:

private MyObject myObj = null;

and at some point in the future:

public void initMyObj(){
    if (myObj == null){
        myObj = new MyObj();
    // do something with myObj

After this, I might reassign myObj to a different object, but it is unlikely. In Scala, I have this:

class Test {
    var myObj: MyObj = _

I've read that I could use Option instead, something like:

var myObj = None : Option[MyObj]

and then my check:

myObj match {
  case None => ...
  case Some(value) => ...

but it feels ackward to use this pattern when I might not make this kind of check anywhere else at any other time - though being so new to Scala, I might be wrong. Is this the best way to achieve what I want or is there any other option not involving Option?

share|improve this question
add comment

2 Answers

up vote 4 down vote accepted

It is not generally ideal practice in Scala to leave partially-constructed objects lying around. You would normally rethink how your objects were getting instantiated to see if you can't use a different pattern that is less fragile. For example, instead of setting uninitialized variables in methods:

class Foo { var a: String = null; var b: String = null }
def initFooA(s: String, f: Foo) { if (f.a == null) f.a = s }
def initFooB(s: String, f: Foo) { if (f.b == null) f.b = s }
initFooA("salmon", f)
// Do stuff
initFooB("herring", f)

you would attempt to restructure your code to generate the values you need on demand, and delay the instantiation of foo until then:

case class Bar(a: String, b: String) {}
def initBarA(s: String) = s
def initBarB(s: String) = s
val iba = initBarA("halibut")
// Do stuff
val ibb = initBarB("cod")
Bar(iba, ibb)

Because Scala has easy access to tuples (and type inference), this can be a lot less painful than in Java.

Another thing you can do is defer the late initialization to someone else.

case class Baz(a: String)(bMaker: => String) {
  lazy val b = bMaker

Now you pass in something that will make parameter b, and arrange for it to handle any late initialization stuff that needs to be handled. This doesn't always avoid needing to set vars, but it can help push it out of your class code into your initialization logic (which is usually a better place for it).

Doing this with vars is a little less straightforward. Realistically, you're probably best off just devoting a class to it e.g. by:

class LazyVar[A](initial: => A) {
  private[this] var loaded = false
  private[this] var variable: A = _
  def apply() = { if (!loaded) { loaded = true; variable = initial }; variable }
  def update(a: A) { loaded = true; variable = a }

where you then (sadly) have to use () on every read and write.

scala> val lv = new LazyVar({ println("Hi!"); 5 })
lv: LazyVar[Int] = LazyVar@2626ea08

scala> lv()
res2: Int = 5

scala> lv() = 7

scala> lv()
res4: Int = 7

Then you use an instance of this class instead of the actual var and pass through the lazy initializer. (lazy val is very much like this under the hood; the compiler just protects you from noticing.)

Finally, if you want to have a fully-functional object that is occasionally missing a value, var x: Option[X] is the construct you want to use; if you can't find a way around the standard Java creation patterns (and you don't want to try something more exotic like objects that create each other with more and more information, either because performance is critical and you can't afford it, or you dislike writing that much boilerplate to allow type-checking to verify that your object is properly created) but you otherwise want to use it, var x: X = null is what I'd choose, not _. If X is a primitive, you probably need to choose the correct value wisely anyway (for example, Double.NaN instead of 0.0, -1 rather than 0 for Int) to indicate I-am-not-initialized. If it's generic code and you want Any instead of AnyRef, asInstanceOf-ing back and forth between Any and AnyRef is probably the best way out of poorly typechecked situation (assuming you really, really can't use Option, which at that point is much clearer).

share|improve this answer
Thanks Rex. I like the late initialization deferral. In my case, I need to initialize a variable. Is it possible to use lazy initialization in some other way? –  Dan Jan 18 '13 at 16:44
@Dan - Sort of; I've amended my answer. –  Rex Kerr Jan 18 '13 at 16:55
add comment

Maybe a lazy variable is what you need.

lazy val myObj: MyObj = //here you put the object creation code

In this way the object creation is postponed to the first time the code tries to access it.

share|improve this answer
isn't lazy just allowed for value definitions? not vars? –  Dan Jan 18 '13 at 16:42
@Dan: Correct. There is only lazy val not "lazy var". –  Randall Schulz Jan 18 '13 at 16:56
My fault, sorry for the typo –  pagoda_5b Jan 18 '13 at 17:00
add comment

Your Answer


