Static variables within a class

0 views
Skip to first unread message

Chat

unread,
Nov 3, 2010, 10:06:47 AM11/3/10
to Principles and Practices of Parallel Programming
I was wondering how you would define a static variable within a
class. Something like doing "public static int count = 0;" in java.

I tried "static var" but when compiling I get an error message that
all static variables must be defined as final.

If I change it to static val, I get an error saying the value cannot
be changed.

Thoughts?

I basically want the class to have a static value that can be changed.

Yoav Zibin

unread,
Nov 3, 2010, 10:14:18 AM11/3/10
to coms49...@googlegroups.com
Hi,
You can box the value, e.g.,
class Box {
  var count:Int = 0;
}
class Foo {
  public static val counter = new Box();
  ...
  counter.count++;
  ...

Chatura Atapattu

unread,
Nov 3, 2010, 10:17:27 AM11/3/10
to coms49...@googlegroups.com
So what happens if I follow it up with this:

var test = new Box();
console.out.println(test.count);

Will that print 0 or 1?  And is this approach the only way to have a static variable within a class? To create a static object of that class and make any persistent changes you want propagated to the non-static objects to the static object?

Yoav Zibin

unread,
Nov 3, 2010, 10:18:35 AM11/3/10
to coms49...@googlegroups.com
yes
Reply all
Reply to author
Forward
0 new messages