In Scala, when we pass parameters to a function they are evaluated before being passed. This is called by-value parameters, and it is default mechanism.
But there may be certain scenarios when we would prefer that parameters are evaluated only when they are used in function body. This helps in building custom control structures.
This is achieved by declaring parameters to be passed using by-name mechanism.
In above method, we define parameters with ': =>' instead of ': '(space after : is necessary). This tells Scala to evaluate parameters only when used in function body. Now we can call this method as:
condition and body both are evaluated only when used in method body. If condition is evaluated to true, body is executed.
This is also helpful when a parameter evaluation is computationally expensive or time consuming as it ensures that evaluation happens only when needed.
By-name parameter mechanism should not be confused with lazy evaluation. Lazy evaluation happens only once when it is needed.
But there may be certain scenarios when we would prefer that parameters are evaluated only when they are used in function body. This helps in building custom control structures.
This is achieved by declaring parameters to be passed using by-name mechanism.
def myWhileLoop(condition: => Boolean)(body: => Unit): Unit = if (condition) { println("Condition passed") body myWhileLoop(condition)(body) }
In above method, we define parameters with ': =>' instead of ': '(space after : is necessary). This tells Scala to evaluate parameters only when used in function body. Now we can call this method as:
var i = 4myWhileLoop (i > 0) { println(i) i -= 1} // prints 4,3,2,1
condition and body both are evaluated only when used in method body. If condition is evaluated to true, body is executed.
This is also helpful when a parameter evaluation is computationally expensive or time consuming as it ensures that evaluation happens only when needed.
By-name parameter mechanism should not be confused with lazy evaluation. Lazy evaluation happens only once when it is needed.
No comments:
Post a Comment