This page is no longer maintained — Please continue to the home page at

Re: Local variable in the primary constructor

No replies
Seth Tisue
Joined: 2008-12-16,
User offline. Last seen 34 weeks 3 days ago.

>>>>> "j" == j romildo writes:

j> How do I declare a local var in the primary constructor without
j> making it a member?
j> For instance,
j> class Test(n: Int) { var x = 0 var i = 0 while (i < n) { x = x + i
j> i = i + 1 } def test = println(x) }
j> object MakeTest { def main(args: Array[String]) { val t = new
j> Test(9) t.test } }
j> The i variable should be local to the primary constructor and not a
j> member. How to accomplish this?

The most minimal change I can think of that works is:

class Test(n: Int) {
var x = 0;
var i = 0
while (i < n) {
x = x + i
i = i + 1
def test() = println(x)

Note the semicolon after "var x = 0"; a blank line works too.

But I think it's clearer and more Scala-ish like this:

class Test(n: Int) {
var x = {
var initialX = 0
var i = 0
while (i < n) {
initialX = initialX + i
i = i + 1
def test() = println(x)

This way, instead having a code block that's just sort of floating
around, it's explicit that the purpose of the code block is to compute
the initial value for x. And if x doesn't need to be modified except at
construction time, you can now make it a val instead of a var, which is
a win.

I realize this is just silly example code, but at the risk of seeming

If this were real code, I would write it like this:

class Test(n: Int) {
val x = (1 until n).foldLeft(0)(_ + _)

The "i" and "initialX" variables have become the first and second
underscores, respectively... or maybe it's the other way around, I can
never remember. In functional code like this, the issue you originally
asked about will hardly ever arise.

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland