How to import multiple members in Scala (wildcard and curly braces syntax)

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is one the shorter recipes, Recipe 7.2, “How to import multiple members in Scala (wildcard and curly braces syntax).”

Problem

You want to import one or more members into the scope of your current Scala program.

Solution

This is the syntax for importing one Scala class:

import java.io.File

You can import multiple classes the Java way:

import java.io.File
import java.io.IOException
import java.io.FileNotFoundException

Or you can import several classes the Scala way:

import java.io.{File, IOException, FileNotFoundException}

Use the following syntax to import everything from the java.io package:

import java.io._

The _ character in this example is similar to the * wildcard character in Java.

If the _ character feels unusual at first, it helps to know that it’s used consistently throughout the Scala language as a wildcard character, and that consistency is very nice.

Discussion

The concept of importing code into the current scope is similar between Java and Scala, but Scala is more flexible. Scala lets you:

  • Place import statements anywhere, including the top of a class, within a class or object, within a method, or within a block of code
  • Import classes, packages, or objects
  • Hide and rename members when you import them

Syntactically, the two big differences are the curly brace syntax, known as the import selector clause, and the use of the _ wildcard character instead of Java’s * wildcard. The advantages of the import selector clause are demonstrated further in Recipes 7.3 and 7.4.

Placing import statements anywhere

In Scala you can place an import statement anywhere. For instance, because Scala makes it easy to include multiple classes in the same file, you may want to separate your import statements so the common imports are declared at the top of the file, and the imports specific to each class are within each class specification:

package foo

import java.io.File
import java.io.PrintWriter

class Foo {
    import javax.swing.JFrame  // only visible in this class
    // ...
}

class Bar {
    import scala.util.Random   // only visible in this class
    // ...
}

You can also place import statements inside methods, functions, or blocks:

class Bar {
    def doBar = {
        import scala.util.Random
        println("")
    }
}

See Recipe 7.6, “Using Scala Import Statements Anywhere”, for more examples and details about the use of import statements.