Constructors in Scala

Category : Scala | Sub Category : Scala Programs | By Prasad Bonam Last updated: 2023-10-10 04:17:11 Viewed : 271


In Scala, constructors are defined in the class body, and you can have both primary constructors and auxiliary constructors. Here are examples of both:

Primary Constructor Example:

In Scala, the primary constructor is defined within the class header. It is the constructor that is called when you create an instance of the class.

scala
class Person(name: String, age: Int) { println(s"Creating a person named $name aged $age") // Other class members can go here }

In this example, name and age are constructor parameters, and they are used to initialize the class members. When you create a Person object, the primary constructor is invoked automatically, and the println statement is executed.

scala
val person = new Person("Alice", 30)

Auxiliary Constructor Example:

In addition to the primary constructor, Scala allows you to define auxiliary constructors using the this keyword. Auxiliary constructors are secondary constructors that provide alternative ways to create instances of the class.

scala
class Person(name: String, age: Int) { println(s"Creating a person named $name aged $age") // Auxiliary constructor def this(name: String) { this(name, 0) // Calls the primary constructor with a default age of 0 } // Other class members can go here }

In this example, we define an auxiliary constructor that takes only a name parameter and sets the age to a default value of 0. The auxiliary constructor calls the primary constructor using this(name, 0).

You can create a Person object using either the primary or auxiliary constructor:

scala
val person1 = new Person("Alice", 30) // Using the primary constructor val person2 = new Person("Bob") // Using the auxiliary constructor

Constructor Overloading Example:

You can overload constructors by defining multiple auxiliary constructors with different parameter lists.

scala
class Person(name: String, age: Int) { println(s"Creating a person named $name aged $age") def this(name: String) { this(name, 0) // Calls the primary constructor with a default age of 0 } def this() { this("Unknown") // Calls the auxiliary constructor with a default name } // Other class members can go here }

In this example, we have two auxiliary constructors: one that takes a name parameter and another that takes no parameters. Each auxiliary constructor calls either the primary constructor or another auxiliary constructor.

scala
val person1 = new Person("Alice", 30) // Using the primary constructor val person2 = new Person("Bob") // Using the first auxiliary constructor val person3 = new Person() // Using the second auxiliary constructor

These examples demonstrate how to define primary and auxiliary constructors in Scala, as well as how to overload constructors to provide flexibility in object creation.

Search
Related Articles

Leave a Comment: