Variable Evaluation Rules in Scala

Sudarshan Kasar
1 min readDec 11, 2020

--

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 1

val 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
// 10

callByName({
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)
}
}

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Sudarshan Kasar
Sudarshan Kasar

No responses yet

Write a response