gpt4 book ai didi

scala - 按名称参数与匿名函数

转载 作者:行者123 更新时间:2023-12-03 13:31:19 25 4
gpt4 key购买 nike

仍然不清楚的是,在延迟评估和其他好处(如果有的话)方面,与匿名函数相比,名称参数的优势是什么:

def func1(a: => Int)
def func2(a: () => Int)

我应该什么时候使用第一个,什么时候使用第二个?

这不是 What's the difference between => , ()=>, and Unit=> 的副本

最佳答案

懒惰在这两种情况下是相同的,但有细微的差别。考虑:

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())

但是,按名称调用的函数对于制作 DSL 很有用。例如:
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
}

关于scala - 按名称参数与匿名函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19948598/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com