HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to ScalaVariables (val / var)Data TypesStringsListsConditions (if / match)Loops (for / while)Functions
REFERENCE
📖 Overview
🖥️ Output
📦 Variables & Types
🔢 Numbers & Math
✍️ String
📚 Collection
🔀 Condition & Loop
🧩 Function
Scala›Loops (for / while)

Loops (for / while)

Iterating over ranges and collections with for, conditional repetition with while.

Simple enough for a 5-year-old to understand

range with for

the range written with to also includes the last number; until does not.

Example code
1
for i <- 1 to 5 do
From 1 to 5, including 5.
LoopFrom 1 to 5, including 5.
2
println(i)
Prints the number in each iteration.
Output / InputPrints the number in each iteration.
LoopOutput / Input
💡 Hint: If you don't want the last number to be included, use until instead of to.

Loop over a list

Example code
1
val languages = List("Scala", "Java")
2
for lang <- languages do
Takes each element in order.
LoopTakes each element in order.
3
println(lang)
Loop

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.Which numbers does the range 1 to 5 include?

About this topic

In Scala, loops are written with for and while, but both are rarely seen in everyday code. In the functional approach, repetition is done via collection methods: mapping, filtering, and reducing replace loops.

The for construct in Scala is actually not a loop, but a readable syntax for collection operations. When you want to produce a result, the yield keyword is added and the construct returns a new collection.

The thing to watch out for when writing ranges is the boundaries: one syntax includes the upper bound, while the other excludes it. When working with collection indices, the exclusive form is correct, because the last index is one less than the number of elements.

What you will learn

  • the for construct and ranges
  • Inclusive and exclusive boundaries
  • The yield keyword
  • the while loop
  • The role of collection methods

Who is this for?

  • Scala developers learning to write loops
  • Those who make mistakes with range boundaries
  • Those transitioning to functional patterns

When to use?

If an independent operation is applied to each element, collection methods are both shorter and more readable than a loop.

When you need to repeat side-effecting operations, such as printing line by line, the for construct is suitable.

Common mistakes

Wrong

val liste = List("a", "b", "c")
for (i <- 0 to liste.length) {
  println(liste(i))
}

Because an inclusive range is used, the loop accesses an invalid index on the last step and an IndexOutOfBoundsException is thrown. Valid indices range from zero to one less than the length; you need to use an exclusive range or iterate directly over the elements.

Correct

val liste = List("a", "b", "c")
for (eleman <- liste) {
  println(eleman)
}

Wrong

val liste = List(1, 2, 3)
val kareler = for (x <- liste) {
  x * x
}
println(kareler)

Because the yield keyword is not written, the construct does not produce a value and the result is an empty value. This keyword is mandatory if you want to obtain a new collection; forgetting it silently returns an empty result.

Correct

val liste = List(1, 2, 3)
val kareler = for (x <- liste) yield x * x
println(kareler)

Wrong

var i = 0
while (i < 5) {
  println(i)
}

Since the counter is not incremented, the condition remains true forever and the program never ends. You have to ensure progression in while loops; this is one of the reasons why this loop is rarely used in Scala.

Correct

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

Frequently asked questions

How do I break out of a loop early?

There is no direct break command in Scala; you need to use a library construct. The more idiomatic way is to turn the condition into a filter or use a method that finds the first matching element.

Can multiple sources be used in a for construct?

Yes, when you write multiple generators, all combinations are traversed, creating a nested loop effect. You can also add conditions in between; this is much more readable than writing nested blocks.

How can I access both the index and the element together?

An indexing method converts a collection into pairs and provides the sequence number and value together at each step. There is no need to maintain a manual counter and the risk of boundary errors is eliminated.

Summary

Inclusive and exclusive ranges are different.

The exclusive form is correct when working with indices.

No result is produced without the yield keyword.

You must ensure progress in a while loop.

Collection methods replace loops.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code