What does this code do? Why is there two sets of constructor parameters?
class A(val x: Int)(val y: Int)
I can initialize an object and use both fields:
val a = new A(5)(7)
println(a.x + ", " + a.y)
If I make it a case class, I can match only by the first set of parameters.
case class A(x: Int)(y: Int)
val a = A(5)(7)
a match {
A(x) => println(x)
}
It's not possible to create 3 sets of parameters. It doesn't compile. So what is the meaning of the two sets of constructor parameters?
There are two types of constructor in Scala – Primary and Auxiliary. Not a special method, a constructor is different in Scala than in Java constructors. The class' body is the primary constructor and the parameter list follows the class name.
A scala class can contain zero or more auxiliary constructor. The auxiliary constructor in Scala is used for constructor overloading and defined as a method using this name. The auxiliary constructor must call either previously defined auxiliary constructor or primary constructor in the first line of its body.
In Scala, we are allowed to make a primary constructor private by using a private keyword in between the class name and the constructor parameter-list.
In Scala, a Primary Constructor is a Constructor which starts at Class definition and spans complete Class body. We can define Primary Constructor with zero or one or more parameters. Now, we will discuss them one by one with some simple examples. Example-1:-Create a Person class with default Primary Constructor.
According to the scala specification (see section 5.3), the second set of parameters is dedicated to implicit parameters. Dividing the parameters in two sets allow you to define only non-implicit paameter and let the other be contextually defined.
It is quite strange actually that the compiler accpet non-implicit parameters in the second set.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With