简体   繁体   中英

Scala anonymous function syntax using partial application?

I'm learning specs2 testing framework by following some of its examples.

I've noticed the following anonymous function syntax is recurring:

val upper = (_: String).toUpperCase

which is equivalent to more conventional / usual

val upper = (s: String) => s.toUpperCase

Although the syntax is simple and elegant, yet it's not very familiar ( easy ) .

Can someone step me through how the first syntax works / derives? I'm pretty sure that it has to do with some sort of partial application but cannot reason fully.

Also is the syntax used frequently in Scala ? (I'm still learning the ropes here :] )

Edit::

I've found the recurring pattern to use such syntax is with ad-hoc polymorphism (simply, overloaded methods / functions) where argument type of the passed function determines what function is dispatched.

For example,

def f(g: Int => String): String = g(10)
def f(g: String => String): String = g("hello")
f((_: Int).toString + " beers") // 10 beers 
f((_: String) + " world") // hello world

This kind of pattern is recurring in libraries like ScalaCheck .

The syntax indicates the compiler you're creating a function with a parameter of type String , which is inserted where the _ is used, according to parameter order. If you had:

val f = (_:String).length + (_:Int) 

it would create a function (String, Int) => Int , where each _ marks where the parameter is being used. The order is important! They must be used in the same order you want the function's parameters to be

If the types are already defined when declaring the val , you can omit them in the function body:

val f: (String, Int) => Int = _.length + _

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