按名称参数与匿名函数 [英] By-name parameter vs anonymous function
本文介绍了按名称参数与匿名函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
仍然不清楚的是,在延迟评估和其他好处(如果有的话)方面,按名称参数相对于匿名函数的优势是什么:
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
}
这篇关于按名称参数与匿名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文