How to Understand the Static Members in Scala
In this article, we will learn about static members in Scala.
Now, Scala is more object-oriented than Java, but unlike Java, we don’t have the static
keyword in Scala. So the solution is to either use companion objects or singleton objects.
Singleton Objects in Scala
As Scala does not have the static
keyword, we can use the concept of a singleton object. A singleton object is a type of object that defines a single object for the class.
This provides an entry point for the execution of the program. If a singleton object is not created in the program, the code would compile but will not give any output.
The singleton object is created using the object
keyword.
Syntax:
object name
{
//our code..
}
Example code:
object Example
{
// Variables of singleton object
var name = "My name is tony stark";
var language = "We are learning Scala language";
// Method of singleton object
def display()
{
println(name);
println(language);
}
}
// Singleton object whose name is main
object Main
{
def main(args: Array[String])
{
//calling the method
Example.display();
}
}
Output:
My name is tony stark
We are learning Scala language
Explanation:
We have created two singleton objects in the above code, i.e., Example
and Main
. The Example
object contains a method named display()
, which is called inside the Main
object directly using the object name Example
instead of creating an object and then calling it.
Here are some important points about singleton objects:
- The
Main
method should always be present when working with singleton objects. - We cannot create an instance of a singleton object.
- Methods inside singleton objects have global accessibility.
- A singleton object can extend classes and traits.
Companion Objects in Scala
We define instances, i.e., non-static members in a class, and define members that we want to appear as static
members in an object with the same name as the class. This kind of object is known as a companion object, and the class is known as the companion
class.
The companion object and the class should be defined in the same source file.
Example code:
class Example
{
var name = "My name is tony stark";
var language = "We are learning Scala language";
def display()
{
println(name);
println(language);
}
}
object Example
{
def main(args: Array[String])
{
//calling the method
var obj = new Example();
obj.display()
}
}
Output:
My name is tony stark
We are learning Scala language