1

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.

Daniel Shin
  • 5,086
  • 2
  • 30
  • 53

1 Answers1

2

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 + _
Chirlo
  • 5,989
  • 1
  • 29
  • 45
  • Your last sentence makes everything clear. 'If the types are already defined when declaring val, you can omit them in the function body'. Although I'm familiar with using `_` to pass anonymous function to combinators, yet this syntax looked eerie because it creates function with not pre-defined types. Thanks! – Daniel Shin Sep 28 '15 at 11:39