In Scala, a class's primary constructor has no explicit body, but is defined implicitly from the class body. How, then, does one distinguish between fields and local values (i.e. values local to the constructor method)?
For example, take the following code snippet, a modified form of some sample code from "Programming in Scala":
class R(n: Int, d: Int) { private val g = myfunc val x = n / g val y = d / g }
My understanding is that this will generate a class with three fields: a private "g", and public "x" and "y". However, the g value is used only for calculation of the x and y fields, and has no meaning beyond the constructor scope.
So in this (admittedly artificial) example, how do you go about defining local values for this constructor?
By contrast, Scala has two types of variables: val creates an immutable variable (like final in Java) var creates a mutable variable.
The primary constructor can have zero or more parameters. The parameters of parameter-list are declared using var within the constructor then the value could change. Scala also generates getter and setter methods for that field.
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.
E.g.
class R(n: Int, d: Int) { val (x, y) = { val g = myfunc (n/g, d/g) } }
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