我做了一个单元测试来研究Scala函数的字面格式,发现它很混乱,你能帮我理解不同语法的含义吗?
@Test def supplierLiteral: Unit = {
object Taker {
def takeFunctionLiteral(supplier: => Int): Unit = {
println("taker takes")
// println(supplier.apply()) //can't compile
println(supplier)
}
def takeExplicitFunction0(supplier: () => Int): Unit = {
println("taker takes")
println(supplier())
}
}
val give5: () => Int = () => {
println("giver gives")
5
}
println(give5.isInstanceOf[Function0[_]])
Taker.takeFunctionLiteral(give5) //can't compile, expected Int
println()
Taker.takeExplicitFunction0(give5)
}为什么takeFunctionLiteral中的println(suppiler.apply())语法不正确?两者不是等同的吗?它们之间的区别是什么
supplier: () => Int和
supplier: => Int提前谢谢。
发布于 2016-10-13 00:05:26
这里supplier: () => Int的supplier类型是一个Function0[Int]。但是在这里,supplier的类型是一个Int。
supplier: => Int (a)和supplier: Int (b)之间的区别在于,在(a)情况下,供应商参数是按名称传递给函数的,并且只有在从函数内部访问时才会进行计算。在(b)情况下,在调用函数的行上计算供应商参数。
https://stackoverflow.com/questions/39999227
复制相似问题