For in loop
A sequence of values, and the loop that takes them one at a time, with no index or counter.
Counting up to a number is one thing; going through values is another. For the second, you first need somewhere to keep them.
@entry(start)
object MyProgram {
start() {
var temperatures := [12, 19, 7];
for reading in temperatures {
Console.print(text: $"reading: {reading}");
}
}
}
Several values under one name
var temperatures := [12, 19, 7];
The brackets gather several values into one — an array. Here three integers, in that order,
under the name temperatures. As with an ordinary variable, the type follows by itself: the
compiler reads three integers and works out an array of integers.
All the values in an array share the same type. You do not mix numbers and texts in one: an
array of texts is written ["a", "b"], and it will never take a number.
for … in … takes the values one at a time
for reading in temperatures {
At each turn, reading holds the next element. No index, no counter, no condition to write: the
loop stops when the array runs out, and you never have to know how many it held.
Compare with the previous sub-section. There, a counter had to be initialised, the condition written, the advance remembered — three chances to get it wrong, the most classic being to stop one notch too early or too late. Here those three do not exist.
reading is local to the loop, like the i of a counting for.
Which to choose
for … inwhenever you are going through values. That is the common case, and the one that reads.- counting
forwhen it is the position you care about and not the value — counting backwards, stepping by two, or needing the index itself.
break and continue work in both, identically.
Your turn
- Add a fourth reading to the array: the loop takes it without anything else being touched. That is the whole point.
- Make an array of texts —
var names := ["Simon", "Magus"];— and go through it. - Print only the readings above 10, with an
ifin the body. - Leave the loop at the first reading above 15, with
break.