kotlin

Is Kotlin "pass-by-value" or "pass-by-reference"?


As I know Java is pass-by-value from this post. I am from Java background I wonder what Kotlin is using for passing values in between. Like in Extensions or Methods etc.


Solution

  • It uses the same principles like Java. It is always pass-by-value, you can imagine that a copy is passed. For primitive types, e.g. Int this is obvious, the value of such an argument will be passed into a function and the outer variable will not be modified. Please note that parameters in Kotlin cannot be reassigned since they act like vals:

    fun takeInt(a: Int) {
        a = 5
    }
    

    This code will not compile because a cannot be reassigned.

    For objects it's a bit more difficult but it's also call-by-value. If you call a function with an object, a copy of its reference is passed into that function:

    data class SomeObj(var x: Int = 0)
    
    fun takeObject(o: SomeObj) {
        o.x = 1
    }
    
    fun main(args: Array<String>) {
        val obj = SomeObj()
        takeObject(obj)
        println("obj after call: $obj") // SomeObj(x=1)
    }
    

    You can use a reference passed into a function to change the actual object.