I'm wondering if it has something that works like static variable inside a function in C.
In C language we have this:
void next_x()
{
static int x = 0;
x++;
}
Variable x
is declared and initialized inside a function. As far I know C - it can be used only in the scope of this function and it is initialized only in first call of this function.
I need something like this in Kotlin. I have code similar to this:
private val x: Int = 0
fun getNextX() : Int {
x++;
return x;
}
and I would like to have something like this:
fun getNextX() : Int {
static val x: Int = 0 // this is not Kotlin code
x++;
return x;
}
I want to:
- Limit
x
variable scope to emphasize that this object is only used by this function and protect it from changes from outside - Initialize it only once
- Keep value/state between function calls
Example above was simplified. In fact I need something like this for ArrayList with limited scope, but retaining state.
I realize that we have singleton pattern which is almost perfect for such needs (except limited scope), but maybe Kotlin offers something else?