Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What replaces class variables in scala?

Tags:

static

scala

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?

like image 479
paradigmatic Avatar asked Dec 11 '09 15:12

paradigmatic


People also ask

How do I declare a class variable 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.

What is difference between class and object in Scala?

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.

What is difference between Val and VAR in Scala?

The difference between val and var is that val makes a variable immutable — like final in Java — and var makes a variable mutable.

What is the equivalent of a static class in Scala?

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.


1 Answers

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) } 
like image 108
Thomas Jung Avatar answered Oct 09 '22 06:10

Thomas Jung