2

I'm following the scala tutorial.

In function literal, it has a following notation:

(_ : *type*) => println("pressed")

For example,

(_ : Int) => println("pressed")

In this notation, I couldn't understand what (_ : type) means.

user7159879
  • 637
  • 2
  • 8
  • 14

1 Answers1

4

It's an anonymous function with an ignored parameter. In Scala the convention is to use an underscore whenever you're not using a parameter.

You could rewrite the exact same thing like this:

(unused: Int) => println("pressed")

As to why someone would want to do this; oftentimes you need to appease Scala's type inference. So if you only wrote

_ => println("pressed")

then Scala wouldn't be able to infer the type of the input parameter. Typing it as

(_: Int) => println("pressed")

assures that the type inferred by the compiler is Int => Unit.

Luka Jacobowitz
  • 22,795
  • 5
  • 39
  • 57