Scala Primary Constructor In-Depth

Filed Under: Scala

In this post, we are going to discuss about Scala Primary Constructor in depth with real-time scenario examples.

Post Brief TOC

  • Introduction
  • Primary Constructor in Scala
  • Scala val and var in-brief
  • Scala Primary Constructor With val and var
  • Scala Primary Constructor in-brief

Introduction

As we know, Constructor is used to create instances of a class. Scala supports constructors in different way than in Java.

In Scala Language, a class can have two types of constructors:

  • Primary Constructor
  • Auxiliary Constructor

A Scala class can contain only Primary Constructor or both Primary Constructor and Auxiliary Constructors. A Scala class can contain one and only one Primary constructor, but can contain any number of Auxiliary constructors. We will discuss Primary Constructor in-detail in this post and Auxiliary Constructor in-detail in my coming post.

Before going to next sections, we need to understand Class Definition and Class Body as shown in the diagram below:

class_definition

Class Body is defined with two curly braces “{ }”. First line is Class Definition.

Primary Constructor in Scala

In Scala, a Primary Constructor is a Constructor which starts at Class definition and spans complete Class body.

We can define Primary Constructor with zero or one or more parameters. Now, we will discuss them one by one with some simple examples.

Example-1:-Create a Person class with default Primary Constructor.


class Person{
      // Class body goes here
}

Here we have defined No-Argument or Zero-Arguments constructor like “Person()”. It is also known as “Default Constructor” in Java.

We can create an instance of Person class as shown below:


 val p1 = new Person()
 
 var p2 = new Person

Both are valid in Scala. We can use No-Arguments constructor without parenthesis.

Example-2:-
Primary Constructor’s parameters are declared after the class name as shown below:


class Person(firstName:String, middleName:String, lastName:String){
      // Class body goes here
}

Here Person class’s Primary Constructor has three parameters: firstName, middleName and lastName.

Now, We can create an instance of Person class as shown below:


 val p1 = new Person("First","","Last")

If we observe this example, some People may have Middle Name or not but still they have to provide all 3 parameters. It is not efficient way to deal with constructors in Scala. We can use Auxiliary Constructors to solve this problem (Please go through my next post).

Example-3:-
Anything we place within the Class Body other than Method definitions, is a part of the Primary Constructor.


class Person(firstName:String, middleName:String, lastName:String){
      println("Statement 1")

      def fullName() = firstName + middleName + lastName

      println("Statement 2")
}

When we execute above program in Scala REPL, we can get the following output:


scala> var p1 = new Person("Ram","","Posa")
Statement 1
Statement 2
p1: Person = Person@3eb81efb

If we observe that output, as both println statements are defined in Class Body, they become the part of Primary Constructor.

Example-4:-:-
Any Statements or Loops (like If..else, While,For etc) defined in the Class Body also become part of the Primary Constructor.


class Person(firstName:String, middleName:String, lastName:String){
      
      def fullName() = firstName + middleName + lastName

      if (middleName.trim.length ==0)
          println("Middle Name is empty.")
}

Output:-


scala> var p1 = new Person("Ram","","Posa")
Middle Name is empty.
p1: Person = Person@64a40280

Example-5:-:-
Not only Statements or Expressions, any method calls defined in the Class Body also become part of the Primary Constructor.


class Person(firstName:String, middleName:String, lastName:String){
      
      def fullName() = firstName + middleName + lastName

      fullName   // A No-argument Method Call
}

Output:-


scala> var p1 = new Person("Ram","-","Posa")
Ram-Posa
p1: Person = Person@64a40280

Scala val and var in-brief

Before discussing about Scala Primary Constructor, we need to revisit about Scala Field definitions concept.

In Scala, “val” and “var” are used to define class fields, constructor parameters, function parameters etc.

  • “val” means value that is constant. “val” is used to define Immutable Fields or variables or attributes.
  • Immutable fields means once we create we cannot modify them.
  • “var” means variable that is NOT constant. “var” is used to define Mutable Fields or variables or attributes.
  • Mutable fields means once we create, we can modify them.

Scala Primary Constructor With val and var

In Scala, we can use val and var to define Primary Constructor parameters. We will discuss each and every scenario with simple examples and also observe some Scala Internals.

We have defined three different Scala sources files as shown below:

primary_constructor_files

Example-1:-
In Scala, if we use “var” to define Primary Constructor’s parameters, then Scala compiler will generate setter and getter methods for them.

Person1.scala


class Person1(var firstName:String,
             var middleName:String, 
             var lastName:String)

Open command prompt at Source Files available folder and compile “Person1.scala” as shown below:

compile_Person1

This step creates “Person1.class” file at same folder. “javap” command is the Java Class File Disassembler. Use this command to disassemble “Person1.class” to view its content as shown below:

Person1_javap_output

As per this output, we can say that “var” is used to generate setter and getter for constructor parameters.

As per Scala Notation, setter and getter methods for firstName Parameter:

Getter Method


public java.lang.String firstName();

Setter Method


public void firstName_$eq(java.lang.String);

This “firstName_$eq” method name is equal to “firstName_=”. When we use “=” in Identifiers Definition(Class Name, Parameter Name, Method names etc.), it will automatically convert into “$eq” Identifier by Scala Compiler.

NOTE:-
Scala does not follow the JavaBeans naming convention for accessor and mutator methods.

Example-2:-
In Scala, if we use “val” to define Primary Constructor’s parameters, then Scala compiler will generate only getter methods for them.

Person2.scala


class Person1(val firstName:String,
             val middleName:String, 
             val lastName:String)

Open command prompt, compile and use “javap” to disassemble to see the generated Java Code as shown below:

Person2_javap_output

If we observe this output, we can say that “val” is used to generate only getter for constructor parameters.

As per Scala Notation, getter methods for firstName, middleName and lastName Parameters:

Getter Methods


public java.lang.String firstName();
public java.lang.String middleName();
public java.lang.String lastName();

Example-3:-
In Scala, if we don’t use “var” and “val” to define Primary Constructor’s parameters, then Scala compiler does NOT generate setter and getter methods for them.

Person3.scala


class Person1(firstName:String,
              middleName:String, 
              lastName:String)

Open command prompt, compile and use “javap” to disassemble to see the generated Java Code as shown below:

Person3_javap_output

If we observe this output, we can say that no setter and getter methods are generated for firstName, middleName and lastName Constructor Parameters.

Scala Primary Constructor in-brief

The Scala Primary Constructor consist of the following things:

  • The constructor parameters declare at Class Definition
  • All Statements and Expressions which are executed in the Class Body
  • Methods which are called in the Class Body
  • Fields which are called in the Class Body

In Simple words, anything defined within the Class Body other than Method Declarations is a part of the Scala Primary Constructor.

That’s it all about Scala Primary Constructor. We will discuss Scala Auxiliary Constructors in-depth in coming posts.

Please drop me a comment if you like my post or have any issues/suggestions.

Comments

  1. Vijay Rajgor says:

    Simply The Best Keep it up Sir ..

  2. arun says:

    This s excellent, everything about constructors on one page..thanks

  3. Kadimi Balu says:

    Am searching Google for the constructors in Scala and i read so many blogs but this is the best information with simple examples Thanks you

  4. vijay says:

    Example 5 is not working….

    class Person(firstName:String, middleName:String, lastName:String){

    def fullName() = firstName + middleName + lastName

    fullName // A No-argument Method Call
    }

    OUTPUT ::
    scala> new Person(“H”,”E”,”MAN”)
    res0: Person = Person@4e302a4b

    method call is not called in the primary constructor… I am using 2.10 version…
    Is it updated in the newer version

  5. kavya says:

    very well explained

  6. ldp says:

    Great post! It helps me a lot. Now I understand how to write the constructor correctly in scala. Looking forward to your next post!

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages