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.
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)
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