I am using _
as placeholder for creating anonymous function, and the problem is I cannot predict how Scala is going to transform my code. More precisely, it mistakenly determines how "large" the anonymous function I want.
List(1,2,3) foreach println(_:Int) //error !
List(1,2,3) foreach (println(_:Int)) //work
List(1,2,3) foreach(println(_:Int)) //work
Using -Xprint:typer
I can see Scala transforms the first one into "a big anonymous function":
x$1 => List(1,2,3) foreach(println(x$1:Int))
the worked 2th 3th are right transformation into what I want.
... foreach (x$1 => println(x$1:Int))
Why this? What's the rule ?
An anonymous function is a function that is not stored in a program file, but is associated with a variable whose data type is function_handle . Anonymous functions can accept multiple inputs and return one output. They can contain only a single executable statement.
Anonymous Function is a function that does not have any name associated with it. Normally we use the function keyword before the function name to define a function in JavaScript, however, in anonymous functions in JavaScript, we use only the function keyword without the function name.
In Python, an anonymous function is a function that is defined without a name. While normal functions are defined using the def keyword in Python, anonymous functions are defined using the lambda keyword. Hence, anonymous functions are also called lambda functions.
What is an anonymous function? Anonymous function is a function define as not bound to an identifier. Because,These are a form of nested function in allowing access to variables in the scope of the containing function (non-local functions). So,This means anonymous functions need to be implemented using closures.
Simple rules to determine the scope of underscore:
So, by the rule #1, instead of println((x: Int) => x)
, the scope will be placed outside (including) println
.
By rule #2, the latter two examples will have the function delimited by parenthesis, so (x => println(x: Int))
.
By rule #3, the first example will be the whole expression, as there are no delimiting parenthesis.
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