if, for, yield, foreach & while in Scala

IFScala_logo

Example of conditional use where it determines whether a note is approved or suspense

var x = 6
 if (x > = 5) {
 println ("approved")
 } else {}
 println ("Substeno")
 }
X: Int = 6
Approved

 

FOR

Example of using “for” where it shows how to go through a list in Scala.

var list = list (1, 2, 3, 4, 5, 6)
for (n<- list) 
  println (N)
List: List[Int] = List (1, 2, 3, 4, 5, 6)
1
2
3
4
5
6

 

FOREACH

Example of use “foreach” where it shows how to traverse a vector in Scala.

val v = Vector((1,2), (3,4), (5,6), (7,8), (9,0))
v.foreach{ case(i,j) => println(i, j) }
v: scala.collection.immutable.Vector[(Int, Int)] = Vector((1,2), (3,4), (5,6), (7,8), (9,0))
(1,2)
(3,4)
(5,6)
(7,8)
(9,0)

 

FOR YIELD

Example of use “for yield” where it shows how to traverse an array in Scala.

val mi_array = Array(1,2,3,4,5)
for (x <- mi_array) yield x * 2
res: Array[Int] = Array(2, 4, 6, 8, 10)

 

WHILE

Example of use “while” where it shows how to traverse an array in Scala.

var x = 5;
 while( x < 10 ){
   println( "Value: " + x )
   x = x + 1
 }
X: Int = 5
Value: 5
Value: 6
Value: 7
Value: 8
Value: 9