0n4li
0n4li

Reputation: 337

Scala package object constructor

When and how is the Scala Package object constructor called?

I have two classes:

Package.scala

package my;
package object entities {
   //Some initialization code in constructor
}

Classy.scala

package my.entities;
case class Classy {
}

I am trying to have the entities constructor to have already been executed by the time an object of Classy is created.

Upvotes: 3

Views: 729

Answers (1)

Péter Török
Péter Török

Reputation: 116306

The package object is translated into a normal java class file called package.class IIRC. From then on I assume it behaves like any normal Java class, thus it is loaded and instantiated when it is first referenced. In Scala, that means you need to define some method or val in the package object, then access it from outside. In your case, you may try calling it from the constructor of Classy, or from the code which instantiates Classy.

Update

OK, here is some code I ran to test what I described above:

// package.scala
package some

package object pkg {
  println("package created!")

  def func() { println("func called") }
}

// C.scala
package some.pkg

class C {
  println("created C")
}

// G.scala
package some.pkg

object G {
  println("creating G")
  func()
  println("created G")
}

// PackageTester.scala
package some.pkg

object PackageTester extends App {
  val c = new C
  val g = G
}

And the output is:

created C
creating G
package created!
func called
created G

Which proves that Scala package objects are created lazily, only when they are actually referenced. And in fact the same is true for "normal" Scala objects, as demonstrated by G above.

Upvotes: 5

Related Questions