In Java I sometimes use class variables to assign a unique ID to each new instance. I do something like
public class
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.
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)
}