我发现按名称参数和函数非常相似。第一个比第二个有什么优势?
object ws1 {
def myByFunc(f: () => Int) = f() //> myByFunc: (f: () => Int)Int
def myByName(f: => Int) = f //> myByName: (f: => Int)Int
def testFunc(a: Int) = a * a //> testFunc: (a: Int)Int
myByFunc(() => testFunc(123)) //> res0: Int = 15129
myByName(testFunc(123)) //> res1: Int = 15129
}
更新:关于他们每个人执行多少次的问题:
object ws1 {
def myByFunc(f: () => Int) = {
println("111111111 myByFunc")
f()
} //> myByFunc: (f: () => Int)Int
def myByName(f: => Int) = {
println("22222222 myByName")
f
} //> myByName: (f: => Int)Int
def testFunc(a: Int) = a * a //> testFunc: (a: Int)Int
myByFunc(() => testFunc(123)) //> 111111111 myByFunc
//| res0: Int = 15129
myByName(testFunc(123)) //> 22222222 myByName
//| res1: Int = 15129
}
由于某种原因,它们都执行了 1 次。为什么?
UPDATE2: 他们都没有被评估:
object ws1 {
def myByFunc(f: () => Int) = {
println("111111111 myByFunc")
} //> myByFunc: (f: () => Int)Unit
def myByName(f: => Int) = {
println("22222222 myByName")
} //> myByName: (f: => Int)Unit
def testFunc(a: Int) = {
println("hello from test func")
123456
} //> testFunc: (a: Int)Int
myByFunc(() => testFunc(123)) //> 111111111 myByFunc
myByName(testFunc(123)) //> 22222222 myByName
}