How to rename members on import in Scala

This is an excerpt from the 1st Edition of the Scala Cookbook (partially modified for the internet). This is a short recipe, Recipe 7.3, “How to rename members on import in Scala.”

Problem

You want to rename Scala members when you import them to help avoid namespace collisions or confusion.

Solution

Give the class you’re importing a new name when you import it with this import syntax:

import java.util.{ArrayList => JavaList}

Then, within your code, refer to the class by the alias you’ve given it:

val list = new JavaList[String]

You can also rename multiple classes at one time during the import process:

import java.util.{Date => JDate, HashMap => JHashMap}

Because you’ve created these aliases during the import process, the original (real) name of the class can’t be used in your code. For instance, in the last example, the following code will fail because the compiler can’t find the java.util.HashMap class:

// error: this won't compile because HashMap was renamed during the import process
val map = new HashMap[String, String]

Discussion

As shown, you can create a new name for a class when you import it, and can then refer to it by the new name, or alias. The book Programming in Scala, by Odersky, et al (Artima), refers to this as a renaming clause.

This can be very helpful when trying to avoid namespace collisions and confusion. Class names like Listener, Message, Handler, Client, Server, and many more are all very common, and it can be helpful to give them an alias when you import them.

From a strategy perspective, you can either rename all classes that might be conflicting or confusing:

import java.util.{HashMap => JavaHashMap}
import scala.collection.mutable.{Map => ScalaMutableMap}

or you can just rename one class to clarify the situation:

import java.util.{HashMap => JavaHashMap}
import scala.collection.mutable.Map

As an interesting combination of several recipes, not only can you rename classes on import, but you can even rename class members. As an example of this, in shell scripts I tend to rename the println method to a shorter name, as shown here in the REPL:

scala> import System.out.{println => p}
import System.out.{println=>p}

scala> p("hello")
hello