Home > Software design >  Does Kotlin have something like static variable inside a function?
Does Kotlin have something like static variable inside a function?

Time:11-22

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:

  1. Limit x variable scope to emphasize that this object is only used by this function and protect it from changes from outside
  2. Initialize it only once
  3. 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?

CodePudding user response:

There isn't anything similar to that in Kotlin, but to simulate a similar effect, you can declare an object with all your static variables as properties, and put the function body in an invoke operator:

object NextX {
    private var x = 0
    operator fun invoke() = x  
}

You basically create an object, but syntactically, it works like a function that you can call:

fun main() {
    println(NextX()) // 0
    println(NextX()) // 1
    println(NextX()) // 2
}

If you think of the entire object as your function, then x is indeed only accessible within the "function".

CodePudding user response:

Functions in Kotlin are stateless, so this is not possible out of the box.

You can get creative though, by having an object with a function which returns the function you desire.

val foo: () -> Int = object {
  var x = 0
  fun createFunc() = fun() = x  
}.createFunc()

foo() // 0
foo() // 1

Note how x doesn't even have to be private, because the object itself cannot be referenced.

This would meet your criteria.

  • Related