Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

262
Views
Kotlin understanding missing var keyword in for loop

I am a beginner in Kotlin and going through for loop

Simple code sample:

 for (i in 1..5) print(i)

Please can someone advise me why we do not specify the counter/iterator variable type "i" with the keyword var / val. Since "var /val" is the standard way to declare variables in Kotlin.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

This is simply how the for loop syntax is designed. I cannot speak for the designers, but I believe that's a design decision to avoid unnecessary bloat, and maybe confusion.

You cannot use an existing variable as the loop variable. The loop variable is scoped to the loop, and shadows existing ones from outer scopes. So it's kind of implied that you're declaring a new variable here, even without a keyword (however I have to admit that the shadowing behaviour would be clearer if we had to write the val/var keyword here).

Also, the loop variable is actually a val inside the loop's body (it cannot be reassigned), but it can feel like a var because it changes for each loop turn and is technically declared outside the loop's body. In effect, it's like a new val declared in the loop's body with a new value for each loop iteration.

So your example code can be thought of as:

var temp = 1
while (temp <= 5) {
    val i = temp
    println(i)
    temp++
}

That's probably why the designers decided to not put any keyword here: it's unnecessary, and both val and var would be confusing in their own way.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!