milo
milo

Reputation: 61

What’s the difference between ‘x: () => Int’ and ‘x: => Int’

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’?

Upvotes: 0

Views: 153

Answers (2)

Shankar Shastri
Shankar Shastri

Reputation: 1154

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.

Upvotes: 2

Phasmid
Phasmid

Reputation: 953

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))

Upvotes: 0

Related Questions