Reputation:
I try to test this in Scala Console (I mean console not script file):
while i < 10 {print(i) i += 1}
It doesn't work. I tried multiple lines it doesn't seem to either.
Am I obliged to use a script file just to test a simple loop ?
Upvotes: 0
Views: 930
Reputation: 17629
As usual, there is more than one way to do this:
// join values beforehand and print the string in one go
println(0 to 9 mkString("\n"))
// using foreach
(0 to 9).foreach(println)
// using for
for(i <- 0 to 9) println(i)
Upvotes: 6
Reputation: 3158
On the other hand, Scala encourages you to not use a mutable variable and while + condition
If you want to print the numbers from 0 to 9, use a sequence comprehension :
for (var <- range ) doSomethingWith (var)
In your case will be:
for (i <- 0 to 9) print (i)
(yes, the example looks pretty silly, but it helps to transition to a more "Scalaish" code)
Upvotes: 1
Reputation: 297205
scala> while i < 10 {print(i) i += 1}
<console>:1: error: '(' expected but identifier found.
while i < 10 {print(i) i += 1}
^
As indicated by the error message, a while must be followed by an "(", as the condition it tests for must be enclosed inside parenthesis. The same thing holds true for "if" and "for", by the way.
Upvotes: 4
Reputation: 14557
What you want is this:
var i = 0; while (i < 10) { print(i); i += 1 };
Upvotes: 2
Reputation: 29701
Yes it's possible. You have some syntax errors though:
var i = 0
while (i < 10) { println(i); i += 1 }
Or on multiple lines:
var i = 0
while (i < 10) {
println(i)
i += 1
}
Upvotes: 10