Search code examples
javascalajvm-languages

Adding default package imports


In Java, Scala, or generally any JVM language, there is a set of packages that is imported by default. Java, for instance, automatically imports java.lang, you don't need to do it in your Java code file.

Now I don't know which component takes care of this exactly (the compiler? the JVM?), but is there any way to have additional packages or even classes imported by default?

Say you have a package defining a set of utility functions you use throughout your project (an example could be scala.math in Scala), it would be great if you were able to skip the import for it in every math related class.


Solution

  • Scala, as of 2.8, has package objects, the contents of which are automatically imported into every file of the package. Create a file called package.scala in the top level directory of your package (e.g., x/y/z/mypackage), and put into it

    package x.y.z
    
    package object mypackage {
      ...
    }
    

    Then any definition within the package object is automatically imported (i.e., no import statement is needed) into any file in package x.y.z.mypackage

    You can take a look at the Scala sources -- do a find dir -name package.scala -- there are a bunch of them, the topmost defining the implicit imports for the scala package itself, which are automatically imported into every scala source file.