
Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
Last updated: March 19, 2024
In this quick tutorial, we’re going to see when the Kotlin compiler fails with the “val cannot be reassigned” error on function 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.
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.