Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an anonymous function to a method value?

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?

like image 751
Lasf Avatar asked Jun 26 '14 00:06

Lasf


People also ask

Can you assign a anonymous function to a variable?

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.

Can you assign an anonymous function to a variable and pass it as an argument to another function?

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.

How do you make an anonymous function?

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.

What is the point of anonymous functions?

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.


1 Answers

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.

like image 60
Hugh Avatar answered Sep 19 '22 06:09

Hugh