How to hide a class (or classes) with Scala import statements

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 7.4, “How to hide a class (or classes) with Scala import statements.”

Problem

You want to hide one or more Scala classes while importing other members from the same package.

Solution

To hide a class during the import process, use the renaming syntax shown in Recipe 7.3, “Renaming Members on Import”, but point the class name to the _ wildcard character.

The following example hides the Random class, while importing everything else from the java.util package:

import java.util.{Random => _, _}

This can be confirmed in the REPL:

scala> import java.util.{Random => _, _}
import java.util.{Random=>_, _}

// can't access Random
scala> val r = new Random
<console>:10: error: not found: type Random
       val r = new Random
                   ^

// can access other members
scala> new ArrayList
res0: java.util.ArrayList[Nothing] = []

In that example, the following portion of the code is what “hides” the Random class:

import java.util.{Random => _}

The second _ character inside the curly braces is the same as stating that you want to import everything else in the package, like this:

import java.util._

Note that the _ import wildcard must be in the last position. It yields an error if you attempt to use it in other positions:

scala> import java.util.{_, Random => _}
<console>:1: error: Wildcard import must be in last position
       import java.util.{_, Random => _}
                         ^

This is because you may want to hide multiple members during the import process, and to do, so you need to list them first.

To hide multiple members, list them before using the final wildcard import:

scala> import java.util.{List => _, Map => _, Set => _, _}
import java.util.{List=>_, Map=>_, Set=>_, _}

scala> new ArrayList
res0: java.util.ArrayList[Nothing] = []

This ability to hide members on import is useful when you need many members from one package, and therefore want to use the _ wildcard syntax, but you also want to hide one or more members during the import process, typically due to naming conflicts.

The Scala Cookbook

This tutorial is sponsored by the Scala Cookbook, which I wrote for O’Reilly:

You can find the Scala Cookbook at these locations:

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.