Is it possible to have immutable parameters for fu...
# getting-started
t
Is it possible to have immutable parameters for functions in Kotlin?
r
Not sure I understand the question. You can’t reassign parameters in Kotlin. If the type of the parameter is immutable (like
String
) then you won’t be able to mutate the value it references, if it’s mutable (like
MutableList
) then you will.
t
I meant whether it's possible to have a function like below or not:
fun foo(val a:Int) = a + 2;
I get: error: 'val' on function parameter is prohibited.
r
Perhaps try it? https://play.kotlinlang.org/ (The answer is yes and no - you can't use that syntax, it has to be
fun foo(a: Int) = a + 2
but
a
will not be reassignable, which is all that using
val
when defining a variable does)
t
Ah, so function parameters are const by default.
r
One thing to look out for is that Kotlin does allow name shadowing:
Copy code
fun foo(a: Int): Int {
    var a = a
    a = a + 2
    return a
}
t
Seems odd.
k
Ah, so function parameters are const by default.
Not just by default. They are always non-reassignable. (I wouldn't use the term "const" as that is a keyword that can only be used in certain contexts.) Unlike C, C++ and C#, you can never reassign a parameter inside a function.