In Scala, you can define package objects. It seems thus that you can access that package object by writing the package name, and then `package`:
// file package.scala in src/com
package com
package object test {
val Version = 2
}
// file Test.scala in src/test
package test
object Test {
def main(args: Array[String]) {
val p = com.test.`package` // get ref on package object
val v1 = com.test.`package`.Version // (1) get val
val v2 = com.test.Version // (2) get val
}
}
What is the difference between (1) and (2)? In some cases, I’ve had to write the extra `package` for my code to run. Should there be a difference or is it a compiler bug?
Moreover, what does e.g. this line mean, in Predef.scala?
scala.`package` // to force scala package object to be seen.
Just a blind guess: The line
results in a simple
getstatic(the package object code) followed bypop. So it is doing nothing more but initialising the package object if it wasn’t already initialised before.So my guess is that in
Predef.scalayou cannot be sure (or it may be definite that it has not happened) that the package object has been initialised already. Most other modules may implicitly depend onPredefbeing loaded, so these modules cannot just be initialised blindly. Therefore one needs to ensure this by including the module/package/object explicitly inPredef. Same is done for the List module and StringBuilder. So, it might just be an initialisation order thing.