7.3. Renaming Members on Import

Problem

You want to rename 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 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). The book 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. ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.