![]() |
VOOZH | about |
Constructors are used to initializing the object’s state. Like methods, a constructor also contains a collection of statements(i.e. instructions). statements are executed at the time of object creation. When our Scala program contains only one constructor than that constructor is called a primary constructor.
The primary constructor and the class share the same body, means we need not to create a constructor explicitly.
Syntax:
class class_name(Parameter_list) {
// Statements...
}
Some important points about primary constructor in Scala -
Let's understand it better with some examples.
Example #1: A primary constructor with parameter-list
Output:
Language name: Scala Topic name: Constructors Total published articles:14
In above example Lname, Tname and article are the parameter of the primary constructor and display is the function to print values.
Example #2: A primary constructor with parameter-list.
Output:
Welcome to Geeksforgeeks
In above example, we can see compiler will automatically create a primary constructor when we create an object of our class, this constructor is known as a default primary constructor.
Example #3: Primary constructor with default values
Output:
Language name: Scala Topic name: Constructors
Example #4: Primary constructor private by using a private keyword.
Output:
Welcome to GeeksForGeeks.
As we can see in above example, private keyword is used in between the class name and the constructor parameter-list. val gfg = new GFG (this line of code) won't even compile because the primary constructor is private.