Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use Scala's `package` special identifier?

Tags:

package

scala

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.
like image 321
Jean-Philippe Pellet Avatar asked Jul 05 '11 10:07

Jean-Philippe Pellet


2 Answers

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.

like image 63
Debilski Avatar answered Nov 11 '22 17:11

Debilski


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.

like image 36
Jan van der Vorst Avatar answered Nov 11 '22 17:11

Jan van der Vorst