Immutable Function Parameters With Kotlin 1.1


#1

Been playing around with Kotlin 1.1 Beta and discovered that any function that contains one or more parameters treats them as immutable. With Kotlin 1.0.x all function parameters are mutable. What is the rationale behind this?

Is the final version of Kotlin 1.1 going to continue with immutable function parameters? Doing so would break backwards compatibility! If immutable function parameters are going to be part of Kotlin 1.1 (stable version when it arrives) then it needs to be mentioned in the release notes.


#2

There is in fact no such difference. Function parameters were immutable in Kotlin 1.0 and are still immutable in Kotlin 1.1.


#3

Yole - You are correct that function parameters are immutable (with an
ordinary Kotlin program) however that isn’t the case when using the Kotlin
REPL (in v1.0.6 but not in v1.1 Beta). Take the following example:


val aStr = "Sample String"

fun mutate(param: String): String {
    param = "Mutated"
    return param
}

mutate(aStr)


#4

This is a bug in the Kotlin REPL, not a language feature.


#5

I think, what you are referring to is called “final” or “non-final” parameter. function parameters in Kotlin have been always “final”. meaning one cannot re-assign them within function.

mutability or immutability depends on how the type (class) is defined. If the type is mutable, then you can in fact change it inside function. example:

data class Foo(var name: String)

fun muteFoo(f: Foo) {
    f.name = "Bar"
}

fun main(args: Array<String>) {
    val foo = Foo("Foo")
    println(foo)                              // prints Foo(name=Foo)

    muteFoo(foo)
    println(foo)                              // prints Foo(name=Bar)
}

in the above example, Foo is mutable and when is passed to a function like (muteFoo), its state can be altered.


#6

Can this thread be moved to the general category?


#7

Do note that the bug also persists in the Kotlin 1.1 Beta REPL.