Scala: Importing Java classes and packages (import syntax, examples)

Summary: This brief tutorial shows Scala import statement syntax examples.

I was just trying to develop a little Java/Swing application in Scala, and right away I ran into the problem of how to import Java classes and packages into a Scala application. 

In short, the following code shows how to import a Java class into a Scala application:

package imports

import javax.swing.JFrame

object jframe {
  def main(args: Array[String]) {
    val f = new JFrame
    f.setVisible(true)
  }
}

As you can see, once you import the JFrame class you can access it directly from your Scala code.

(There are other, preferred ways of writing Scala Swing applications, and I'm just using this JFrame example to make it easier for Java programmers who are new to Scala.)

Importing multiple classes

If you want to import multiple classes from a Java package, you can use the usual Java import syntax:

import javax.swing.JFrame
import javax.swing.JDialog

or you can use this Scala import syntax, if you prefer:

import javax.swing.{JFrame, JDialog}

(You'll like this syntax more when you see the "alias" example below.)

Import all classes from a package

If you want to import all classes from a Java package, use this syntax instead:

import javax.swing._

Importing classes using aliases

Another thing I just remembered that you can do when importing Java classes is that you can reference them by a different name, creating an alias for them as you import them:

import java.io.{ FileInputStream, InputStream, File => JFile }

As you can see from this example, which I just copied from the Scala Source object source code, the java.io.File class is imported, and the "File => JFile" lets us refer to the File class as JFile instead.

As you can see, there are several different ways to import Java classes and packages, depending on your needs.