tags:

views:

311

answers:

5

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 ?

+7  A: 

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
}
Jay Conrod
Of course for the same effect there's: for( i <- 0 until 10 ) { println( i ); }, the "while" way of doing it seems unusual in Scala.
Calum
Or the even more succinct "0 until 10 foreach println"
James Iry
+2  A: 

What you want is this:

var i = 0; while (i < 10) { print(i); i += 1 };
Fake Code Monkey Rashid
+2  A: 
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.

Daniel
+1  A: 

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)

GClaramunt
+1  A: 
(0 to 9).map( println )
Matt von Rohr