Home »
Scala
Scala constructors with examples
By IncludeHelp Last updated : October 22, 2024
Scala constructors
A constructor is a function that is called at the time of initialization of objects. A constructor is just like a method of a class that contains instructions to be executed. The constructor has the same name as the class and is called when the object of the class is initialized.
Scala programming language defines two types of constructors,
- Primary constructor
- Auxiliary constructor
1. Primary constructor
Also known as default constructor, a primary constructor is created when no other constructor is defined. It has the same name as the class. It is defined by default in Scala.
Syntax
class class_name(parameter list){
// statements to be executed...
}
Example
class Student(val Sname: String, val Ssubject: String, val percentage: Int) {
def result() : Unit = {
println("Student name: " + Sname)
println("Subject taken: " + Ssubject)
println("Percentage obtained: " + percentage)
}
}
object MyObject {
def main(args: Array[String]) : Unit = {
val obj = new Student("Ramesh", "Maths", 78)
obj.result()
}
}
Output
Student name: Ramesh
Subject taken: Maths
Percentage obtained: 78
2. Auxiliary constructor
In a Scala class, programmers are allowed to create multiple constructors for a single class. But there can be only one primary constructor of a class. Constructor that is explicitly defined by the programmer other than the primary is known as an auxiliary constructor.
Syntax
def this(parameter list){
//code to be executed
}
There can be multiple auxiliary constructors which can be differentiated by their parameter list. In the definition of any auxiliary constructor, the first statement should be a call to the primary constructor or another auxiliary constructor which is defined before the calling constructor using "this" keyword.
Example
class Student(val Sname: String, val sub: String) {
var percentage: Float = 0.0f
def display(): Unit = {
println("Student name: " + Sname)
println("Stream: " + sub)
println("Percentage: " + percentage)
}
def this(Sname: String, sub: String, no: Int) : Unit = {
this(Sname, sub)
this.percentage = no / 5.0f
}
}
object Main {
def main(args: Array[String]) : Unit = {
val obj = new Student("Kirti", "Biology", 345)
obj.display()
}
}
Output
Student name: kirti
Stream : biology
Percentage: 69.0