简体   繁体   中英

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

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM