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?
The variable is declared with the following syntax in Scala as follows: val or val variable_name: variable_datatype = value; In the above syntax, the variable can be defined in one of two ways by using either the 'var' or 'val' keyword. It consists of 'variable_name' as your new variable, followed by a colon.
Difference Between Scala Classes and Objects Definition: A class is defined with the class keyword while an object is defined using the object keyword. Also, whereas a class can take parameters, an object can't take any parameter. Instantiation: To instantiate a regular class, we use the new keyword.
The difference between val and var is that val makes a variable immutable — like final in Java — and var makes a variable mutable.
Scala classes cannot have static variables or methods. Instead a Scala class can have what is called a singleton object, or sometime a companion object.
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) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With