Functions and Loops
Functions:
In Scala, even functions are objects and can be initialized to a value.
If there are multiple statements in the function, it always considers the last line as the return statement.
LOOPS:
FOR LOOP
1. Simple For Loop
object ForDemo{
Simple for loop calls foreach function
2. For Loop with Filter (If Condition)
3. For Loop with yield
4. For Loop with if and yield (When both exist, withFilter has priority)
IF-Else Loop
While Loop
Functions:
In Scala, even functions are objects and can be initialized to a value.
object FuncDemo{
def main(args:Array[String]){
println(product(5,6))
}
def product(n1:Int,n2:Int):Int={
n1*n2
}
}
sh-4.3$ scala FuncDemo.scala
30
If there are multiple statements in the function, it always considers the last line as the return statement.
object FuncDemo{
def main(args:Array[String]){
println(product(5,6))
}
def product(n1:Int,n2:Int):Int={
n1*n2
n1+n2
n2-n1
}
}
sh-4.3$ scala FuncDemo.scala
1
LOOPS:
FOR LOOP
1. Simple For Loop
object ForDemo{
def main(args:Array[String]){
for(i<-1 to 10) println(i)
}
}
sh-4.3$ scala ForDemo.scala
1
2
3
4
5
6
7
8
9
10
Simple for loop calls foreach function
sh-4.3$ scalac -Xprint:parse ForDemo.scala
[[syntax trees at end of parser]] // ForDemo.scala
package <empty> {
object ForDemo extends scala.AnyRef {
def <init>() = {
super.<init>();
()
};
def main(args: Array[String]): scala.Unit = 1.to(10).foreach(((i) => println(i)))
}
}
2. For Loop with Filter (If Condition)
object ForDemo{
def main(args:Array[String]){
for(i<-1 to 10 if i<4) println(i)
}
}
sh-4.3$ scala ForDemo.scala
1
2
3
3. For Loop with yield
object ForDemo{
def main(args:Array[String]){
var retVal = for(i<-1 to 10) yield i*2
for(i<-retVal) println(i)
}
}
sh-4.3$ scala ForDemo.scala
2
4
6
8
10
12
14
16
18
20
4. For Loop with if and yield (When both exist, withFilter has priority)
object ForDemo{
def main(args:Array[String]){
var retVal = for(i<-1 to 10 if i<4) yield i*2
for(i<-retVal) println(i);
}}
sh-4.3$ scala ForDemo.scala
2
4
6
sh-4.3$ scalac -Xprint:parse ForDemo.scala (Hiding unnecessary details)
var retVal = 1.to(10).withFilter(((i) => i.$less(4))).map(((i) => i.$times(2)));
retVal.foreach(((i) => println(i)))
IF-Else Loop
object IfElseDemo{
def main(args:Array[String]){
var x=10
var y=20
if(x<y) println(x) else println(y)
}
}
sh-4.3$ scala IfElseDemo.scala
10
While Loop
object WhileLoopDemo{
def main(args:Array[String]){
var x=1
while(x<10){
println(x)
x+=1
}
}
}
sh-4.3$ scala WhileLoopDemo.scala
1
2
3
4
5
6
7
8
9