Scala Primary Constructor
Scala program which contains only one constructor then that constructor is known as Primary constructor.
The parameters of the primary constructor are use to initialize the class's fields. This means that class fields can be declare directly within the class body using constructor parameters, and these fields are accessible throughout the class.
The primary constructor is invoked when an instance of the class is create. It executes the initialization code defined within the class body, such as initializing fields or executing expressions.
Scala allows flexibility in defining the primary constructor:
- Parameters can be specified directly in the class definition, defining both the constructor parameters and corresponding fields.
- The primary constructor can include access modifiers (e.g.,
val
,var
,private
) to specify visibility and mutability of fields. - Auxiliary constructors (secondary constructors) can be defined using
def this(...)
, which must eventually call the primary constructor.
syntax:-
class class name(parameter list) {
//statements
}
use case 1:
scala> class smartphone(val size:Int, val price:Double){
println("Inside smartphone constructor")
def desc = "smartphone price" + price + "is of size" + size
}
![](https://prwatech.in/blog/wp-content/uploads/2021/04/image-50.png)
use case 2:
scala> class Dog(val size:Int, val height:Double){
println("Inside dog constructor")
def desc = "Dog height" + height + "is of size" + size
}
![](https://prwatech.in/blog/wp-content/uploads/2021/04/image-51.png)
use case 3:
scala> class Fruit(val name:String,val color:String, val weight:Double){
println("Inside dog constructor")
def desc = "Fruit name" + name + "is of color" + color + "and weight is" + weight
}
![](https://prwatech.in/blog/wp-content/uploads/2021/04/image-52.png)