I am trying to read the parameter-list of the following 2 functions:
1. def foo(action: => String => String) = "bar"
2. def foo(action: => () => String => String) = "bar"
=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .
In Scala, functions are first-class values in the sense that they can be: passed to and returned from functions. put into containers and assigned to variables. typed in a way similar to ordinary values. constructed locally and within an expression.
One function can be passed to another function as a function argument (i.e., a function input parameter). The definition of the function that can be passed in as defined with syntax that looks like this: "f: Int > Int" , or this: "callback: () > Unit" .
action
is a passed-by-name function that takes a String
and returns a String
.action
is a passed-by-name function that takes nothing to return a function that takes a String
and returns a String
Now you might ask, "Well, what does it mean for a parameter to be passed-by-name?" Alright... that's a whole different can of worms. Basically, a passed by name parameter is only evaluated when it's used in the function, and every time that it's used in the function. What this allows for is something like short-circuiting, as follows
def orOperator(left: Boolean, right: => Boolean) : Boolean = if (left) true else right
In this case, the operator will short-circuit (and terminate without computing/evaluating right
) if it finds left
to be true.
So... what you have with these parameters is something similar. They are functions that do not evaluate—for some reason—unless/until they are named in the function body. I don't understand the motivation for that, but... that's how it is. I hope that helps.
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