Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala equivalent of C++ static variable in a function

I am quite new to Scala and stumbled across following problem:

what is Scala equivalent of function's static variable ?

void foo()
{
    static int x = 5;
    x++;
    printf("%d", x);
}

EDIT:

What I want to achieve is a kind of function call counter - I want to check how many times my function has been executed and in the same time limit the visibility of this counter so that it can't be modified from outside.

like image 880
tommyk Avatar asked Jan 07 '13 13:01

tommyk


People also ask

What is static variable in Scala?

There are no static variables in Scala. Fields are variables that belong to an object. The fields are accessible from inside every method in the object. Fields can also be accessible outside the object, depending on what access modifiers the field is declared with.

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.

Are there static methods in Scala?

You want to create a class that has instance methods and static methods, but unlike Java, Scala does not have a static keyword.

What can I use instead of a static variable?

Yes, you can use Construct On First Use Idiom if it simplifies your problem. It's always better than global objects whose initialization depend on other global objects.


1 Answers

Scala has no equivalent to the local static variables of C++. In Scala, scoping rules are more consistent than in C++ or Java - what is defined within a block, goes out of scope when the block is exited. As others noted, a local static variable would be a side effect, which is not desirable in functional programming.

Scala, being a hybrid OO/functional language, makes it possible to write in imperative style, but prefers and encourages functional style (e.g. by making immutable collections the default choice). Local static variables, apart from representing a side effect per se, are absent in Java too, which is one more reason not to provide them in Scala.

like image 158
Péter Török Avatar answered Sep 28 '22 01:09

Péter Török