VOOZH about

URL: https://www.geeksforgeeks.org/scala/scala-primary-constructor/

⇱ Scala | Primary Constructor - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Scala | Primary Constructor

Last Updated : 11 Jul, 2025

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 -  

  • The primary constructor can have zero or more parameters.
  • The parameters of parameter-list are declared using var within the constructor then the value could change. Scala also generates getter and setter methods for that field.
  • The parameters of parameter-list are declared using val within the constructor then the value cannot change And Scala also generates only a getter method for that field.
  • The parameters of parameter-list are declared without using val or var in the constructor, then the visibility of the field is very compact and Scala does not generate any getter and setter methods for that field.
  • The parameters of parameter-list are declared using private val or var in the constructor then it prevents from generating any getter and setter methods for that field. So, these fields can be accessed by the members of that class.
  • In Scala, only a primary constructor is allowed to invoke a superclass constructor.

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. 
 

Comment
Article Tags:

Explore