0

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.

Chen Fan
  • 1
  • 2
  • 1
    See http://stackoverflow.com/questions/32802104/some-questions-about-difference-between-call-by-name-and-0-arity-functions – Yawar Oct 12 '16 at 13:01

1 Answers1

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.

ka4eli
  • 5,294
  • 3
  • 23
  • 43