Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you define a local var/val in the primary constructor in Scala?

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?

like image 214
skaffman Avatar asked Jul 13 '09 10:07

skaffman


People also ask

What is Val and VAR in Scala?

By contrast, Scala has two types of variables: val creates an immutable variable (like final in Java) var creates a mutable variable.

What is primary constructor in Scala?

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.

How does Scala define 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.


1 Answers

E.g.

class R(n: Int, d: Int) {   val (x, y) = {     val g = myfunc     (n/g, d/g)   } } 
like image 128
Alexander Azarov Avatar answered Sep 23 '22 01:09

Alexander Azarov