Variable Evaluation Rules in Scala
def x = 2 //evaluated when called
val y = 2 //evaluated immediately
lazy val z = 2 //evaluated once when needed
def callByValue(x: Int)// Evaluates the funtion argument(x)’s before calling the function
def callByName(x: => Double)// Evaluates the funtion then evaluates funtion argument(x)s if needed
object EvaluationRulesScala {
def main(args: Array[String]): Unit = {
//valVarDeclaration 2
println(“****starting the app***”) // ****starting the app***
val defVarDeclarationCall1 = defVarDeclaration // defVarDeclaration 1
val defVarDeclarationCall2 = defVarDeclaration // defVarDeclaration 1val valVarDeclarationCall1 = valVarDeclaration //
val valVarDeclarationCall2 = valVarDeclaration //val lazyValVarDeclarationCall1 = lazyValVarDeclaration // lazyValVarDeclaration 3
val lazyValVarDeclarationCall2 = lazyValVarDeclaration //callByValue({
println(“passing the value “+ 10)
10
}) // passing the value 10
// call by value example
// 10callByName({
println(“passing the value “+ 20)
20
}) // call by name example
// passing the value 20
// 20
}def defVarDeclaration = {
println(“defVarDeclaration “ + 1)
1
}val valVarDeclaration = {
println(“valVarDeclaration “ + 2)
2
}lazy val lazyValVarDeclaration = {
println(“lazyValVarDeclaration “ + 3)
3
}def callByValue(x: Int): Unit = {
println(“call by value example “)
println(x)
}def callByName(x: => Int): Unit = {
println(“call by name example “)
println(x)
}
}