Scala – Primary Constructor

In the previous chapter, we have learnt about package object in scala. Now, we will see constructor and its types in scala.

Constructor is used for creating an instance (object) of a class. Scala has 2 types of constructor and it works in a different way than constructor in Java.

  1. Primary Constructor
  2. Auxiliary Constructor

There are few points that we need to remember as follows.

  • A scala class can have only one primary constructor but any number of auxiliary constructors.
  • A scala class can have either primary constructor or both primary and auxiliary constructors.
  • Not a special method, a constructor is different in Scala than in Java constructors.

We will see both primary and auxiliary constructor in details one by one.

Primary Constructor:

We we create a class, compiler creates a constructor and it will be called automatically while an object is created with that class. A primary constructor can have zero or one or more parameters. Primary constructor with no parameters is also called default constructor. All statements defined inside the class body will be treated as part of the constructor.

Example: Suppose we have a class named as Employee with no parameters. A default constructor will be called when class instance(object) is created.

Primary constructor with parameters:

In the below example, Employee class has three parameters named as firstName, middleName and lastName. Some employees will have middle name and some will not, but we have to pass all three arguments each time we create an object. This is not ideal practice, but it can overcome by using auxiliary constructor which will see in next chapter.

As stated above, all statements like if, while, for loop, function call etc. defined in the class body become part of constructor, except method definition. You can understand with the help of below example.

In next chapter, we will discuss auxiliary constructor.

Scala - Common code in package object
Scala - Auxiliary Constructor
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of He is an automation engineer having more than 8 years of experience who loves troubleshooting in automation and finding innovative ways to solve the problems. His other leisurely activities includes playing harmonica, paintings, sketching portrait, watching movies and travelling etc.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *