Search code examples
scalafunction-literal

What is the scala notation written as _:type?


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.


Solution

  • 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.