Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of underscore in lift[A,B](f: A => B): Option[A] => Option[B] = _ map f

Tags:

scala

I'm working through the examples in Runar and Paul's Functional Programming in Scala book, and I've come 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 don't understand the implementation because I don't understand what the underscore represents. I've looked at many other threads about the myriad meanings of underscore in Scala, and while I'm sure those threads must mention this type of use case, I must've missed it.

like image 755
liminalisht Avatar asked Feb 06 '15 21:02

liminalisht


1 Answers

The underscore here is a shorthand for a function. The compiler is smart enough to infer, based on the return type of the method signature, that what is meant is:

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)
like image 179
Channing Walton Avatar answered Oct 18 '22 09:10

Channing Walton