What exactly that declaration of method parameter means:
def myFunc(param: => Int) = param
What is meaning of =>
in upper definition?
Formal Parameter : A variable and its type as they appear in the prototype of the function or method. Actual Parameter : The variable or expression corresponding to a formal parameter that appears in the function or method call in the calling environment. Modes: IN: Passes info from caller to callee.
Parameter Types Presently, the type is one of ref, const, or val. The type indicates the relationship between the actual argument and the formal parameter. , for a full discussion of references.)
Introduction to TypeScript void type The void type denotes the absence of having any type at all. It is a little like the opposite of the any type. Typically, you use the void type as the return type of functions that do not return a value.
Parameters are the variables in the definition of a function. In other words, they exist in the function signature and will be used as variables in the function body. Arguments are the actual values that were passed to the function when we call it.
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).
Just to make sure there is an answer that uses the proper term: the Scala Language Specification uses the term call-by-name:
The type of a value parameter may be prefixed by =>, e.g. x: => T . The type of such a parameter is then the parameterless method type => T . This indicates that the corresponding argument is not evaluated at the point of function application, but instead is evaluated at each use within the function. That is, the argument is evaluated using call-by-name.
-- Section 4.6.1 of the Scala Language Specification
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With