1. Overview

In this quick tutorial, we’re going to see when the Kotlin compiler fails with the “val cannot be reassigned” error on function parameters.

2. Final Parameters

Function parameters are final in Kotlin. So, we can think of them as read-only local variables and quite similar to a val declaration. Consequently, if we try to reassign a Kotlin function parameter to something else:

fun echo(content: String) {
    content += "Hello"
}

Then the Kotlin compiler will fail with the error:

>> kotlinc main.kt   
main.kt:2:5: error: val cannot be reassigned
    content += "Hello"
    ^

As shown here, the compiler error message clearly states that function parameters are final and that we cannot reassign them to something else.

Technically speaking, this is a good design decision as it can avoid a whole lot of confusion about certain edge cases. In addition to that, final parameters are generally a better practice to follow. Therefore, it’s generally wiser to not look for workarounds for this good limitation.

3. Conclusion

In this very short tutorial, we learned that function parameters are final in Kotlin. As a result, we can’t re-assign some other values to them, and in that regard, they’re like any other variable declared as a val.

2 Comments
Oldest
Newest
Inline Feedbacks
View all comments
Michal
Michal
2 months ago

“As shown here, the compiler error message clearly states that function parameters are immutable and that we cannot reassign them to something else.”

I think this is partially true. Function parameters are final by default and that’s why we cannot reassign them to something else.

If I pass mutableListOf() as a parameter it will not magically became immutable.

Akash Deep
Akash Deep
1 month ago
Reply to  Michal

Thanks for the feedback. We’ve updated the article

Comments are closed on this article!