按名称参数与匿名函数
问题描述:
仍然不清楚的是,在延迟评估和其他好处(如果有的话)方面,按名称参数相对于匿名函数的优势是什么:
What is still unclear for is what's the advantage by-name parameters over anonymous functions in terms of lazy evaluation and other benefits if any:
def func1(a: => Int)
def func2(a: () => Int)
什么时候用第一个,什么时候用第二个?
When should I use the first and when the second one?
答
懒惰在这两种情况下是一样的,但也有细微的差别.考虑:
Laziness is the same in the both cases, but there are slight differences. Consider:
def generateInt(): Int = { ... }
def byFunc(a: () => Int) { ... }
def byName(a: => Int) { ... }
// you can pass method without
// generating additional anonymous function
byFunc(generateInt)
// but both of the below are the same
// i.e. additional anonymous function is generated
byName(generateInt)
byName(() => generateInt())
带有 call-by-name 的函数对于制作 DSL 很有用.例如:
Functions with call-by-name however is useful for making DSLs. For instance:
def measured(block: ⇒ Unit): Long = {
val startTime = System.currentTimeMillis()
block
System.currentTimeMillis() - startTime
}
Long timeTaken = measured {
// any code here you like to measure
// written just as there were no "measured" around
}