Scala function => as parameter

Can someone kindly explain to me why the following

/** * Returns a set transformed by applying `f` to each element of `s`. */ def map(s: Set, f: Int => Int): Set = x => exists(s, y => f(y) == x) 

not equivalent

  def map(s: Set, f: Int => Int): Set = x => exists(s, f(x)) 

where "exists" is a function that returns whether there is a limited integer inside s (first argument) satisfying p (second argument).

Why do you need to specify "y => f (y) == x"? Thanks a million!

+5
source share
1 answer

exists second argument is of type Int => Boolean (right?), in other words, it expects a function from Int to Boolean . Now f(x) does not match this type - it has type Int . So - y => f(y) == x creates a function with the correct type, which returns true if its input is x .

If extra characters cause an error, you can also shorten it a bit with the anonymous argument "_":

 def map(s: Set, f: Int => Int): Set = x => exists(s, f(_) == x) 
+10
source

All Articles