This is an excerpt from the Scala Cookbook (partially modified for the internet). This is a short recipe, Recipe 7.5, “How to use ‘static imports’ in Scala.”
Problem
In Scala, 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 static import approach there’s no need for the leading “Day.” in the code, and it’s easier to read.
this post is sponsored by my books: | |||
#1 New Release |
FP Best Seller |
Learn Scala 3 |
Learn FP Fast |