I have made a unit test to study Scala function literal format and found it quite confusing, could you please help me understand meaning of different syntax?
@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)
}
Why is println(suppiler.apply()) incorrect syntax in takeFunctionLiteral?
Aren't both equivalent? What is the difference between
supplier: () => Int
and
supplier: => Int
Thanks in advance.
Here
supplier: () => Intthe type of thesupplieris aFunction0[Int]. But heresupplier: => Intthe type of thesupplieris anInt.The difference between
supplier: => Int(a) andsupplier: Int(b) is that in case (a) supplier parameter is passed into function by name and will be evaluated only when accessed from inside function. In case (b) supplier parameter is evaluated on the line where function is called.