0

When using these in a function parameters description, they have different effects. Only the latter form can accept multi-line operations like

{
  println(“hello”)
  println(“world”)
  1
}

However, the former can’t.

I know ‘()’ means “no parameters”, right? But what ‘’ means in ‘=>Int’?


Here's the whole story.

Define a function

def func(x: =>Int)= {
  println(x)
}

Invoke it

func {
  println("hello")
  println("world")
  1
}

We will get

hello
world
1

However, if we define the function as

def func(x: ()=>Int)= {
  println(x)
}

Invoke it using the former code, we will get

error: type mismatch;
 found   : Int(1)
 required: () => Int
       1
       ^

So, what's the difference between ‘x: () => Int’ and ‘x: => Int’?

milo
  • 61
  • 4
  • => is used to identify the input and output types. Type at left will be input type and the type at right will be output type of the function. The syntax you're showing is not correct. Could you clarify your question or post some code? – pramesh Jun 16 '18 at 03:19

2 Answers2

2

Behaviors Of Call By Name Evaluation VS Higher-Order Functions

Call By Name Evaluation:

In case of call by name, the expression is evaluated before the function is invoked.

Example:

def func(x: =>Int): Int= {
  x
}

func(10 + 2)

Higher-Order Functions:

In case of HOF, the function is passed and its result are computed when the function is invoked.

Example:

def func(x: () =>Int): () => Int = {
  x
}
func(() => 10 + 2)

Note: Check the return types for more clarity.

Shankar Shastri
  • 1,106
  • 10
  • 17
  • 1
    "evaluated at runtime" should be "evaluated before the function is invoked". All expressions (outside of types and macros) are "evaluated at runtime". – Alvaro Carrasco Jun 16 '18 at 20:04
0

Essentially, there is no difference. Both represent 0-arity functions which result in an Int value.

However, there is a big difference in how they are used. One, x: => Int, is used for a call-by-name parameter in a method and is invoked simply by referencing an Int. The compiler does the rest.

The other form, x: () => Int, is used for a method parameter where you really want to pass in a 0-arity function. But when you use x within your method, you must actually give it parentheses. And, of course, when you invoke the method, you need to pass in a function (or partially-applied method), not an Int.

Here's an example:

def and(a: Boolean, b: () => Boolean): Boolean = if (a) b() else false

def not(): Boolean = false

println(and(true, not))
Phasmid
  • 871
  • 6
  • 19