Back to questions
JuniorTheoryCommon
What happens when you build and run this program?
fun addOne(n: Int): Int {
n = n + 1
return n
}
fun main() {
println(addOne(5))
}It does not compile: a parameter cannot be reassigned
- Expecting
6: treating a parameter as a variable you may change. In Kotlin a parameter is read-only, like aval, son = n + 1does not compile. - Expecting the program to fail only when it runs: the compiler checks every assignment first and reports
'val' cannot be reassigned., so nothing runs.
- How would you change
addOneso that it returns6without assigning ton? - Why does Kotlin make every parameter read-only?