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
scala.`package`
results in a simple getstatic
(the package object code) followed by pop
. 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.scala
you 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 on Predef
being loaded, so these modules cannot just be initialised blindly. Therefore one needs to ensure this by including the module/package/object explicitly in Predef
. Same is done for the List module and StringBuilder. So, it might just be an initialisation order thing.
There is no difference between (1) and (2) in your code. The package object allows you to write it as (2). But you may still write is as (1).
I can only imagine that the cases in which you had to write package
in your code must have to do something with your development environment (Eclipse/Scala plugin?) expecting a class named "package" to stem from a source named "package.scala" and not from "test.scala".
Can you reproduce the cases in which you had to write package
?
I am also curious what the effect of that line is in Predef.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With