Search code examples
functionkotlincompilationparameter-passingstatic-methods

Is there a way to reuse variables in Kotlin in static functions in multiple calls?


I just found that function params are not mutable in Kotlin. I was expecting mutability with no mention of this in official documentation I found. Personally I think there should be some way to reuse a single variable across multiple static functions in Kotlin. How can this be with immutable params? I am trying for not returning values used, just arrays, reuse values like index of it or same variable used in different functions not needing access to data from other functions. Like in other languages a data thing can be passed around and used but maybe not read in other functions, but it supports writing a thing and using it within scope of a static function.

I have tried Kotlin playground, I expected a var param thing, none present. I tried arrays and lists and found in Kotlin playground, members may be set but not origin array or list. My question is whether this would compile or not. With that I could rig all variables to be in arrays or lists and set as I please. Anyway, question is: how can a set of static functions in Kotlin reuse a variable or variables like var in multiple calls? This is for efficiency sake, more variables, more garbage collection, slower programs, and I would prefer a faster program.


Solution

  • Kotlin doesn't support passing function arguments by a reference. Arguments are always copied. It is not supported by the main target platforms of Kotlin as well: Java and JavaScript.

    If you really want to do this, you can create a simple wrapper and pass it around:

    fun test(value: Wrapper<String>) {
        value.value = "foo"
    }
    
    data class Wrapper<T>(var value: T)
    

    However, this is not really a "Kotlin way". In languages like Kotlin or Java we assume functions/methods receive arguments and they return new values. We can modify passed objects and if the name of the function clearly mentions this, this is not considered a bad practice. But returning results through arguments or replacing variables of the caller, is more typical to languages like C, than Kotlin/Java. I believe Kotlin/Native has some support for pointers, so it could be possible there.