Home > Back-end >  how is it possible to Initalize a Val inside a loop?
how is it possible to Initalize a Val inside a loop?

Time:09-15

very very starter here, so not very knewledge. Can anyone explain me why this code in Kotlin below works?

How can I initalize a val inside the loop every iteration??

    val n = readln().toInt()
     
    repeat(n) {
            val next = readln().toInt()
            sum  = next
        }

CodePudding user response:

Variables declared as val cannot change their reference, you'll need to use var for that:

val n = readln().toInt()

var sum = 0
repeat(n) {
    val next = readln().toInt()
    sum  = next
}

println(sum)

Your code already declares a val each iteration. It isn't needed though, you can directly increase sum:

sum  = readln().toInt()

CodePudding user response:

next is not "variable" shared for each loop iterations.

It's declaration in statement scope inside loop.

In other words, next for first iteration and next for second iteration are two independent values.

  • Related