For in Scala
In Scala, we have several ways to create loops:
The
while
loop is used for the most basic type of loop with a single condition.The
for
loop in Scala is more powerful and can be used in various ways. Here, we’ve used it with a range (0 until 3
) which is similar to the Gofor j := 0; j < 3; j++
loop.Scala doesn’t have a direct equivalent to Go’s
for i := range 3
. Instead, we use afor
loop with a range.For an infinite loop, we use
while(true)
. Note that Scala doesn’t havebreak
orcontinue
statements. To achieve similar functionality, you would typically use recursive functions or other control structures. Thebreak
andcontinue
shown in this example are just for illustration and won’t compile in actual Scala code.The last example shows how you might simulate a
continue
in Scala using an if-else structure.
To run this Scala program:
Remember that Scala encourages a more functional programming style, so while these imperative loops are possible, you might often see more functional approaches using methods like map
, filter
, and foreach
on collections.