0

我做了一个单元测试来研究 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)
}

为什么中的println(suppiler.apply())语法不正确takeFunctionLiteral?两者不是等价的吗?和有什么区别

supplier: () => Int

supplier: => Int

提前致谢。

4

1 回答 1

0

Here supplier: () => Int the type of the supplier is a Function0[Int]. But here supplier: => Int the type of the supplier is an Int.

The difference between supplier: => Int (a) and supplier: 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.

于 2016-10-12T16:05:26.363 回答