3 ms·
Scala doesn't have lazy evaluation of function arguments, it's got call-by-name. The difference is that lazy evaluation caches the value an argument evaluates t
by mafribe 11y ago
Scala doesn't have lazy evaluation of function arguments, it's got call-by-name.
The difference is that lazy evaluation caches the value an argument evaluates to the first time it is needed, so it's evaluated at most once, whereas call-by-name simply passes the parameter unevaluated and the result of evaluation is not cached, so might be computed more than once.
Consider this Scala program
object Main extends {
def tryit [ T ] ( block : => T ) : Unit = {
println ( "----- Running 1st block -----" )
block
println ( "----- Running 2nd block -----" )
block
println ( "--------- Finished ----------" ) }
def main ( args : Array [ String ] ) {
var i = -1
tryit ( { i += 1; println ( s"i = $i" ) } ) }
}
- seanmcdirmid 11y agoDoes scala not have lazy vals anymore?
- mafribe 11y agoSorry, I had forgotten about lazy vals. Thanks for reminding me. They are cached, so proper lazy [1], see e.g. https://stackoverflow.com/questions/3041253/whats-the-hidden-cost-of-scalas-lazy-val https://stackoverflow.com/questions/3041253/whats-the-hidden...
- justthistime_ 11y agoHoly shit ... is your space bar broken?