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:
importjava.util.{ArrayList=>JavaList}
Then, within your code, refer to the class by the alias you’ve given it:
vallist=newJavaList[String]
You can also rename multiple classes at one time during the import process:
importjava.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 processvalmap=newHashMap[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:
importjava.util.{HashMap=>JavaHashMap}importscala.collection.mutable. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access