Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two sets of constructor parameters in a scala class

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?

like image 428
PeWu Avatar asked Jul 28 '10 09:07

PeWu


People also ask

How many types of constructors are used in Scala?

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.

What is primary and auxiliary constructor in Scala?

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.

How do I create a class constructor in Scala?

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.

What is primary constructor in Scala?

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.


1 Answers

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.

like image 123
Nicolas Avatar answered Sep 27 '22 20:09

Nicolas