7.5. Using Static Imports
Problem
You want to import members in a way similar to the Java static import approach, so you can refer to the member names directly, without having to prefix them with their class name.
Solution
Use this syntax to import all members of the Java Math
class:
import
java.lang.Math._
You can now access these members without having to precede them with the class name:
scala>import java.lang.Math._
import java.lang.Math._ scala>val a = sin(0)
a: Double = 0.0 scala>val a = cos(PI)
a: Double = −1.0
The Java Color
class also
demonstrates the usefulness of this technique:
scala>import java.awt.Color._
import java.awt.Color._ scala>println(RED)
java.awt.Color[r=255,g=0,b=0] scala>val currentColor = BLUE
currentColor: java.awt.Color = java.awt.Color[r=0,g=0,b=255]
Enumerations are another great candidate for this technique. Given
a Java enum
like this:
package
com
.
alvinalexander
.
dates
;
public
enum
Day
{
SUNDAY
,
MONDAY
,
TUESDAY
,
WEDNESDAY
,
THURSDAY
,
FRIDAY
,
SATURDAY
}
you can import and use this enumeration in a Scala program like this:
import
com.alvinalexander.dates.Day._
// somewhere after the import statement
if
(
date
==
SUNDAY
||
date
==
SATURDAY
)
println
(
"It's the weekend."
)
Discussion
Although some developers don’t like static imports, I find that this approach makes enums more readable. Just specifying the name of a class or enum before the constant makes the code less readable:
if
(
date
==
Day
.
SUNDAY
||
date
==
Day
.
SATURDAY
)
{
println
(
"It's the weekend."
)
}
With the ...
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.