Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a chain of Scala function parameters

Tags:

scala

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"
  1. A function named "foo" which receives a function named "action" which receives/returns ???
  2. A function named "foo" which receives a function named "action" which returns a function which returns ???
like image 467
recalcitrant Avatar asked Dec 28 '11 23:12

recalcitrant


People also ask

What does => mean in scala?

=> 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 .

What is function values in scala?

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.

How do you pass a function to a function in scala?

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" .


1 Answers

  1. action is a passed-by-name function that takes a String and returns a String.
  2. 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.

like image 138
Destin Avatar answered Oct 18 '22 18:10

Destin