Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Scala have static imports like Java? [closed]

Tags:

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?

like image 879
bharal Avatar asked Jan 07 '13 11:01

bharal


People also ask

Does Scala have static?

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 .

Why there is no static in Scala?

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.

Can Scala have static members in its classes?

You want to create a class that has instance methods and static methods, but unlike Java, Scala does not have a static keyword.

What does import do in Scala?

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.


1 Answers

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._
like image 147
Guillaume Avatar answered Oct 11 '22 21:10

Guillaume