With this code
val foo = List('a', 'b', 'c')
aString.forall(foo.contains(_))
IntelliJ highlights foo.contains(_) and suggests "Anonymous function convertible to method value". I have researched eta expansion, but am unable to see how I could improve this particular piece of code. Any ideas?
An anonymous function in javascript is not accessible after its initial creation. Therefore, we need to assign it to a variable, so that we can use its value later. They are always invoked (called) using the variable name. Also, we create anonymous functions in JavaScript, where we want to use functions as values.
They're called anonymous functions because they aren't given a name in the same way as normal functions. Because functions are first-class objects, we can pass a function as an argument in another function and later execute that passed-in function or even return it to be executed later.
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.
The advantage of an anonymous function is that it does not have to be stored in a separate file. This can greatly simplify programs, as often calculations are very simple and the use of anonymous functions reduces the number of code files necessary for a program.
I believe it's saying that you could simply have
val foo = List('a', 'b', 'c')
aString.forall(foo.contains)
Note that we're not explicitly converting the foo.contains
method here to an anonymous function.
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