What Is the Scala Notation Written as _: Type? [Duplicate]

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.

0

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.

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest