- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
object loading and instantiation
Fri, 2012-01-13, 04:36
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
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