Does Scala support static imports, like Java does?
Like, say:
import static java.util.Collections.singleton;
Can I also do the above in Scala? I'm getting a compile error when I try it -- something about a misplaced dot -- so presumably my syntax is incorrect?
Scala classes cannot have static variables or methods. Instead a Scala class can have what is called a singleton object, or sometime a companion object. This example defines a singleton object called Main .
As we know, Scala does NOT have “static” keyword at all. This is the design decision done by Scala Team. The main reason to take this decision is to make Scala as a Pure Object-Oriented Language. “static” keyword means that we can access that class members without creating an object or without using an object.
You want to create a class that has instance methods and static methods, but unlike Java, Scala does not have a static keyword.
Importation in Scala is a mechanism that enables more direct reference of different entities such as packages, classes, objects, instances, fields and methods. The concept of importing the code is more flexible in scala than Java or C++. The import statements can be anywhere.
There are no statics in Scala, the nearest concept is the singleton object. Like a Java static import, you can import all the members of a singleton object.
object MySingleton { .... }
object Main {
import MySingleton._
}
You can also import all the static members of a Java class from Scala, just omit static.
import java.lang.Math._
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With