Unlike ‘for’ loop, while and do-while loop are not expressions, these are pure statements. You can convert a ‘for’ from statement to expression using ‘yield’ keyword, but while, do-while loops are pure statements.
Syntax
while(condition) {
......
......
}
Example: Print even numbers till 10 (exclusive)
while(i < 10){
println(s"i = $i")
i += 2
}
scala> var i = 2
var i: Int = 2
scala> while(i < 10){
| println(s"i = $i")
| i += 2
| }
i = 2
i = 4
i = 6
i = 8
No comments:
Post a Comment