45

In Java I sometimes use class variables to assign a unique ID to each new instance. I do something like

public class Foo {

  private static long nextId = 0;

  public final long id;

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

  [...]

}

How can I do this in Scala?

2 Answers 2

69

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)
}
Sign up to request clarification or add additional context in comments.

Comments

27

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.

3 Comments

Objects don't have to have the same name as classes, only companion objects do.
We tend to use the same name for class and object , as it helps a lot in Debugging the Code.
These two answers should be combined

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.