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

object loading and instantiation

1 reply
null
Joined: 2011-10-25,
User offline. Last seen 51 weeks 1 day ago.

Consider the following REPL session:

scala> class Super { println("Super") }
defined class Super

scala> class Sub extends Super { println("Sub") }
defined class Sub

scala> new Sub
Super
Sub
res0: Sub = Sub@728a728a

scala> object Obj extends Super { println("Obj") }
defined module Obj

For "new Sub" the body of Super and Sub are invoked as expected. But
when I define Obj, neither the body of Obj nor of Super is invoked. Of
course, the first time I access Obj, the bodies are invoked:

scala> Obj
Super
Obj
res1: Obj.type = Obj$@7f707f7

scala> Obj
res2: Obj.type = Obj$@7f707f7

Is it that the loading of Obj is different from its instantiation? Is
it possible to "force" the instantation of Obj as soon as it is
loaded?

== Keyur

Tony Sloane
Joined: 2009-01-07,
User offline. Last seen 2 years 32 weeks ago.
Re: object loading and instantiation

On 13/01/2012, at 2:36 PM, Keyur Shah wrote:

> Consider the following REPL session:
>
>
>
> scala> class Super { println("Super") }
> defined class Super
>
> scala> class Sub extends Super { println("Sub") }
> defined class Sub
>
> scala> new Sub
> Super
> Sub
> res0: Sub = Sub@728a728a
>
> scala> object Obj extends Super { println("Obj") }
> defined module Obj
>
>
>
> For "new Sub" the body of Super and Sub are invoked as expected. But
> when I define Obj, neither the body of Obj nor of Super is invoked. Of
> course, the first time I access Obj, the bodies are invoked:
>
>
>
> scala> Obj
> Super
> Obj
> res1: Obj.type = Obj$@7f707f7
>
> scala> Obj
> res2: Obj.type = Obj$@7f707f7
>
>
>
> Is it that the loading of Obj is different from its instantiation? Is
> it possible to "force" the instantation of Obj as soon as it is
> loaded?

Object definitions are lazy, so they don't get constructed until you use them.

See this SO thread for more discussion and a nontrivial workaround if you really need this behaviour:

http://stackoverflow.com/questions/6249569/force-initialization-of-scala...

cheers,
Tony

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