7.4. Hiding a Class During the Import Process
Problem
You want to hide one or more 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, 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 => _, ...
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.