Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala underscore minimal function

Let's create a value for the sake of this question:

val a = 1 :: Nil

now, I can demonstrate that the anonymous functions can be written in shorthand form like this:

a.map(_*2)

is it possible to write a shorthand of this function?:

a.map((x) => x)

my solution doesn't work:

a.map(_)
like image 625
ryskajakub Avatar asked Dec 12 '10 14:12

ryskajakub


People also ask

What does _ means in Scala?

Scala allows the use of underscores (denoted as '_') to be used as placeholders for one or more parameters. we can consider the underscore to something that needs to be filled in with a value. However, each parameter must appear only one time within the function literal.

What does case _ mean in Scala?

case _ => does not check for the type, so it would match anything (similar to default in Java). case _ : ByteType matches only an instance of ByteType . It is the same like case x : ByteType , just without binding the casted matched object to a name x . – Gregor Raýman.

What does => mean in Scala?

=> is the "function arrow". It is used both in function type signatures as well as anonymous function terms. () => Unit is a shorthand for Function0[Unit] , which is the type of functions which take no arguments and return nothing useful (like void in other languages).

What is anonymous function in Scala?

In Scala, An anonymous function is also known as a function literal. A function which does not contain a name is known as an anonymous function. An anonymous function provides a lightweight function definition. It is useful when we want to create an inline function.


2 Answers

For the record, a.map(_) does not work because it stands for x => a.map(x), and not a.map(x => x). This happens because a single _ in place of a parameter stands for a partially applied function. In the case of 2*_, that stands for an anonymous function. These two uses are so close that is very common to get confused by them.

like image 140
Daniel C. Sobral Avatar answered Oct 19 '22 04:10

Daniel C. Sobral


Your first shorthand form can also be written point-free

a map (2*)

Thanks to multiplication being commutative.

As for (x) => x, you want the identity function. This is defined in Predef and is generic, so you can be sure that it's type-safe.

like image 24
Kevin Wright Avatar answered Oct 19 '22 04:10

Kevin Wright