Home > Articles

This chapter is from the book

12.4 Parameter Inference

When you pass an anonymous function to another function or method, Scala helps you out by deducing types when possible. For example, you don’t have to write

valueAtOneQuarter((x: Double) => 3 * x) // 0.75

Since the valueAtOneQuarter method knows that you will pass in a (Double) => Double function, you can just write

valueAtOneQuarter((x) => 3 * x)

As a special bonus, for a function that has just one parameter, you can omit the () around the argument:

valueAtOneQuarter(x => 3 * x)

It gets better. If a parameter occurs only once on the right-hand side of the =>, you can replace it with an underscore:

valueAtOneQuarter(3 * _)

This is the ultimate in comfort, and it is also pretty easy to read: a function that multiplies something by 3.

Keep in mind that these shortcuts only work when the parameter types are known.

val fun = 3 * _ // Error: Can’t infer types

You can specify a type for the anonymous parameter or for the variable:

3 * (_: Double) // OK
val fun: (Double) => Double = 3 * _ // OK because we specified the type for fun

Of course, the last definition is contrived. But it shows what happens when a function is passed to a parameter (which has just such a type).

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.