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.

I can’t say for sure but if I had to guess it would be for the following reasons:

  1. It’s a well known pattern in programming, used in many languages for decades.
  2. The declaration would be extra boilerplate since ‘var’ makes contextual sense.
  3. Other uses or features left open by keeping the explicit declaration weren’t valuable enough to leave the boilerplate in.

EDIT: Oops, I swapped “val” with “var” in my post :man_facepalming:

1 Like

Thank you Arocnies for your guidance. However for a newbee like me no book/tutorial mentions that you don’t need to specify. No one taks about it and thus confusion. However, i saw some C# code and there also it was explicitly declared.
I do hope Kotlin doesn’t go the old ways of JavaScript where requires lot of efforts to clean up

One more thing, why is counter is of “var” and not “val”

My guess is that val in for would be just redundant. for syntax implies that we define a variable there. The same for function arguments - we don’t do it like this

fun foo(val param1: String, val param2: String)

(I assume you meant the opposite: it is val, not var)

Because changing its value doesn’t make too much sense. Once again, this is similar to function parameters. We received some value from someone and even if we modify it, then with new function call / loop iteration we will just get another value.

Also, this is not really counter. Remember that for in Kotlin isn’t based on counters, but on iterators (well, in some cases they are actually optimized by the compiler to use counters). If you need counters then use while.

There’s no ambiguity on the type of that variable, it’s whatever is in the container. Even if you could specify the type it’d be fully determined by the container.

1 Like

This. I think it’s not declared as val because you don’t have an option to declare it as var. Same for formal parameters.

1 Like