object ScalaDemo extends App{
var n = 10
def count:Int = {
n -= 1
n
}
def invokeByName(x : => Int):Unit = {
println("start")
for (i <- 0 until 3){
println("invokeByName x = " + x) //不能使用x()
}
println("end")
}
def invokeByName2(x : () => Int):Unit = {
println("start")
for (i <- 0 until 3){
println("invokeByName2 x = " + x())
}
println("end")
}
def invokeByValue(x : Int):Unit = {
println("start")
for (i <- 0 until 3){
println("invokeByValue x = " + x)
}
println("end")
}
//统一初始化
invokeByName{
println("begin invokeByName")
count
}
invokeByName2{
println("begin invokeByName2")
() => {
n -= 1
n
}
}
invokeByValue{
println("begin invokeByValue")
count
}
}
输出
start begin invokeByName invokeByName x = 9 begin invokeByName invokeByName x = 8 begin invokeByName invokeByName x = 7 end begin invokeByName2 start invokeByName2 x = 6 invokeByName2 x = 5 invokeByName2 x = 4 end begin invokeByValue start invokeByValue x = 3 invokeByValue x = 3 invokeByValue x = 3 end