Elevator underline value [A, B] (f: A => B): Option [A] => Option [B] = _ map f

I work on Runar and Paul functional programming examples in the Scala book, and I came across the following implementation of the lift function in section 4.3.2:

def lift[A,B](f: A => B): Option[A] => Option[B] = _ map f

I understand the purpose of the function, but I do not understand the implementation, because I do not understand what the underscore is. I looked at many other threads about the myriad underscore values ​​in Scala, and although I'm sure these threads should mention this type of use case, I must have missed it.

+5
source share
2 answers

The underscore here is an abbreviation for the function. The compiler is smart enough to conclude that, based on the return method signature type, the following is implied:

 def lift[A,B](f: A => B): Option[A] => Option[B] = (_: Option[A]).map(f) 

which, in turn, expands to:

 def lift[A,B](f: A => B): Option[A] => Option[B] = (o: Option[A]) => o.map(f) 
+12
source

You might want to see this answer . _ map f is the syntactic sugar for x => x map f , the underscore is a placeholder for an anonymous function argument.

+10
source

Source: https://habr.com/ru/post/1212845/


All Articles