Scala Tutorial

Basics

Control Statements

OOP Concepts

Parameterized - Type

Exceptions

Scala Annotation

Methods

String

Scala Packages

Scala Trait

Collections

Scala Options

Miscellaneous Topics

Scala Constructors

In Scala, constructors are special methods that are executed when an object of a class is instantiated. There are two types of constructors in Scala:

  1. Primary Constructor
  2. Auxiliary Constructor(s)

1. Primary Constructor:

The primary constructor is interwoven with the class definition itself. The parameters of the class are essentially the parameters of the primary constructor.

For instance:

class Person(name: String, age: Int) {
  println(s"$name is $age years old.")
}

In the above example, the primary constructor takes two parameters: name and age. When you create an instance of this Person class, the code inside the class (outside any methods) is also executed, which in this case prints a message.

Additionally, you can add access modifiers to primary constructor parameters:

  • If you use val or var with parameters, they become class fields (i.e., val creates a read-only field, and var creates a mutable field).
  • If a parameter doesn't have val or var, it's just a constructor parameter and won't be accessible as a class field.

2. Auxiliary Constructor(s):

These are additional constructors and are defined with the def keyword followed by this. Auxiliary constructors must either call the primary constructor or another auxiliary constructor as their first action.

Example:

class Person(name: String, age: Int) {
  
  // Primary Constructor Body
  println(s"$name is $age years old.")

  // An auxiliary constructor
  def this(name: String) {
    this(name, 0)  // Calls the primary constructor
    println(s"Age not provided for $name.")
  }
}

Usage:

val person1 = new Person("Alice", 30)  // Alice is 30 years old.
val person2 = new Person("Bob")        // Age not provided for Bob.
                                       // Bob is 0 years old.

Key Points:

  • Every class will have one primary constructor and can have zero or more auxiliary constructors.
  • The primary constructor's body is the entire body of the class.
  • Auxiliary constructors must start by calling another constructor in the same class (either the primary constructor or another auxiliary constructor).
  • To differentiate constructors based on the number/type of parameters, you'd use method overloading, just like with auxiliary constructors.

Constructors, especially in conjunction with features like case classes and companion objects, make Scala a versatile and expressive language for object-oriented programming.

  1. Primary Constructor in Scala:

    The primary constructor is defined along with the class definition.

    class Person(val name: String, var age: Int) {
      // Code in the primary constructor body
    }
    
  2. Auxiliary Constructors in Scala:

    Auxiliary constructors are additional constructors defined using the this keyword.

    class Person {
      def this(name: String, age: Int) {
        // Code in the auxiliary constructor body
      }
    }
    
  3. Parameterized Constructors in Scala:

    Constructors can take parameters for initializing class fields.

    class Person(name: String, age: Int) {
      // Class body
    }
    
    val person = new Person("John", 30)
    
  4. Default Constructors in Scala:

    A default constructor is automatically generated when no constructors are defined.

    class Person {
      // Default constructor
    }
    
  5. Initializing Fields in Scala Constructors:

    Fields can be initialized directly in the constructor parameters.

    class Person(val name: String, var age: Int = 25)
    

    Here, age has a default value of 25.

  6. Chaining Constructors in Scala:

    Constructors can call other constructors using this.

    class Person(val name: String, var age: Int) {
      def this(name: String) {
        this(name, 25) // Call the primary constructor
      }
    }
    
  7. Visibility Modifiers in Scala Constructors:

    You can apply visibility modifiers to constructor parameters.

    class Person(private val name: String, private var age: Int)
    

    Here, name and age are private.

  8. Secondary Constructors vs. Factory Methods in Scala:

    Secondary constructors provide alternative ways to create instances, but factory methods offer more flexibility.

    class Person private (val name: String, var age: Int) {
      def this(name: String) {
        this(name, 25) // Secondary constructor
      }
    }
    
    object Person {
      def createWithDefaultAge(name: String): Person = new Person(name) // Factory method
    }
    

    The factory method createWithDefaultAge provides more control over instance creation.