This page is no longer maintained — Please continue to the home page at www.scala-lang.org

Local variable in the primary constructor

2 replies
j.romildo
Joined: 2009-01-04,
User offline. Last seen 42 years 45 weeks ago.

How do I declare a local var in the primary constructor without making
it a member?

For instance,

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

object MakeTest {
def main(args: Array[String]) {
val t = new Test(9)
t.test
}
}

The i variable should be local to the primary constructor and not a
member. How to accomplish this?

Romildo

Stepan Koltsov
Joined: 2008-12-20,
User offline. Last seen 42 years 45 weeks ago.
Re: Local variable in the primary constructor

class Test(n: Int) {
{
var x = 0
var y = 0
...
}
}

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

extempore
Joined: 2008-12-17,
User offline. Last seen 35 weeks 3 days ago.
Re: Local variable in the primary constructor

On Sun, Jan 04, 2009 at 01:45:20PM -0200, j [dot] romildo [at] gmail [dot] com wrote:
> How do I declare a local var in the primary constructor without making
> it a member?
>
> class Test(n: Int) {
> var x = 0
> var i = 0
> while (i < n) {
> x = x + i
> i = i + 1
> }
> def test =
> println(x)
> }

Open a new scope:

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 extra line of whitespace between var x = 0 and the scope; either an extra line or a semicolon is necessary to keep
the block from being interpreted as a refinement.

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