Scala – Constructors/Modifiers

  • date 8th October, 2020 |
  • by Prwatech |
  • 0 Comments

Scala constructor parameter modifiers

 

Constructor:

1. Primary Constructor – compiler creates a constructor which is known as primary constructor. All the statements of class body treated as part of constructor. It is also known as default constructor.

      Run the following program to execute Primary Constructor:

Output:

2. Scala Secondary (auxiliary) Constructor – Let’s call primary constructor from inside the auxiliary constructor. This keyword is used to call constructor from other constructor. When calling other constructor make it first line in your constructor.

Run the following command to execute secondary (auxiliary) constructor:

OUTPUT:

 

    

In Scala, constructor parameter modifiers provide flexibility and control over how constructor parameters are treated within class definitions. Scala supports various modifiers that can  to constructor parameters to define their visibility, immutability, and other characteristics.

  1. Visibility Modifiers: Constructor parameters can be marked as private or protected to restrict their visibility within the class or its subclasses, respectively. This helps encapsulate class internals and enforce access control.

  2. Immutability Modifiers: Constructor parameters can be declared as val to make them immutable (read-only) after initialization. Immutable constructor parameters ensure that their values cannot be change once set, promoting functional programming principles and thread safety.

    

Modifiers:

1.     No Modifiers

2.     Private

3.     Protected

Accessibility chart:

  Outside Package Same Package Same Class Sub Class Companion Class
No Modifier Yes Yes Yes Yes Yes
Private No No Yes No Yes
Protected No No Yes Yes Yes

 

·  Singleton Object

·  Companion Class

Example program of Singleton Object

 

Scala constructor parameter modifiers

0
0

Quick Support

image image