Function parameter types and =>

PrimosK picture PrimosK · Mar 1, 2012 · Viewed 23.5k times · Source

What exactly that declaration of method parameter means:

def myFunc(param: => Int) = param

What is meaning of => in upper definition?

Answer

Tomasz Nurkiewicz picture Tomasz Nurkiewicz · Mar 1, 2012

This is so-called pass-by-name. It means you are passing a function that should return Int but is mostly used to implement lazy evaluation of parameters. It is somewhat similar to:

def myFunc(param: () => Int) = param

Here is an example. Consider an answer function returning some Int value:

def answer = { println("answer"); 40 }

And two functions, one taking Int and one taking Int by-name:

def eagerEval(x: Int)   = { println("eager"); x; }
def lazyEval(x: => Int) = { println("lazy");  x; }

Now execute both of them using answer:

eagerEval(answer + 2)
> answer
> eager

lazyEval(answer + 2)
> lazy
> answer

The first case is obvious: before calling eagerEval() answer is evaluated and prints "answer" string. The second case is much more interesting. We are actually passing a function to lazyEval(). The lazyEval first prints "lazy" and evaluates the x parameter (actually, calls x function passed as a parameter).

See also