tags:

views:

129

answers:

2

In java I sometimes use class variables to assign an unique id to each new instances. I do something like:

public class Foo {

  private static long nextId = 0;

  public final long id;

  public Foo() {
    id = nextId;
    nextId++;
  }

  [...]

}

How can I reproduce this behaviour in scala ?

+7  A: 

Variables on the companion object:

object Foo{
    private var current = 0
    private def inc = {current += 1; current}
}

class Foo{
    val i = Foo.inc
    println(i)
}
Thomas Jung
+6  A: 

To amplify on Thomas' answer:

The object definition is usually put in the same file with the class, and must have the same name. This results in a single instance of an object having the name of the class, which contains whatever fields you define for it.

A handy do-it-yourself Singleton construction kit, in other words.

At the JVM level, the object definition actually results in the definition of a new class; I think it's the same name with a $ appended, e.g. Foo$. Just in case you have to interoperate some of this stuff with Java.

Carl Smotricz