코를린으로 간단한 for 반복문 코드를 짜다가 에러가 발생했다.
val cannot be reassigned
필자) 문제가 발생한 부분
for (i in 0 until n) {
if( condition ) {
answer[i] = start + i
i++ //val cannot be reassigned 에러 발생
}
}
다른 유저)
How to increment a val in "for loop" in Kotlin when a statement is true
In java we can increment "i' in for loop when a condition is true for(i=0; i<=n; i++){ if(condition) i++ } If I do the increment in Kotlin, it shows that "val cannot be changed". ...
stackoverflow.com
Is it possible to write a for loop in Kotlin where I can change the index to any value I want during the iteration?
Is it possible to write a for loop in Kotlin where I can change the index to any value I want during the iteration? I know I can write a for loop like that: for (i in 1..3) { println(i) } for (...
stackoverflow.com
공식 문서와 스택오버플로우 등에서 이유를 찾아보니
Kotlin for loop header에서 선언된 변수는 암묵적으로 val로 선언된다는 것을 알게 되었다.
val 은 mutable이 아닌데 값을 변경시키려 했기에 에러가 발생했던 것이다.
for (val i in 0 until n) {
if( condition ) {
answer[i] = start + i
i++ //val cannot be reassigned 에러 발생
}
}
위의 예시코드처럼 실제로는 val로 선언된다.
해결법
위의 코드의 로직을 유지하고 싶다면 for문 대신 while문을 사용해야 한다.
var i = 0
while( i < n ) {
if( condtion ) {
answer[i] = start + i
i++
}
}
개인적으로 살짝 불편하다..
댓글