CyberPlayerOne
CyberPlayerOne

Reputation: 3180

Scala: why using `_` as a lambda expression body to be used as a function argument does not work?

For example,

scala> val a = Set(Array(1, 2),Array(8, 9))
a: scala.collection.immutable.Set[Array[Int]] = Set(Array(1, 2), Array(8, 9))

scala> a.flatMap(_)
<console>:9: error: missing parameter type for expanded function ((x$1) => a.flatMap(x$1))
              a.flatMap(_)
                        ^

scala> a.flatMap(x=>x)
res4: scala.collection.immutable.Set[Int] = Set(1, 2, 8, 9)

Is there a shortcut for x=>x type of lambda function?

Upvotes: 1

Views: 139

Answers (3)

Alexey Romanov
Alexey Romanov

Reputation: 170733

Since your title asks why it doesn't work, and not just how to make it work: the error message tells you.

When _ is used directly as an argument of a method, its scope expands so that a.flatMap(_) is x => a.flatMap(x). This is simply useful much more often: would you want println(_) to always print <function1>?

Upvotes: 1

Arpit Suthar
Arpit Suthar

Reputation: 754

It seems you are looking for identity,

val a = Set(Array(1, 2) ,Array(8, 9))

a.flatten

a.map(identity).flatten

If you go into identity its like

@inline def identity[A](x: A): A = x

So it works same as x => x, whatever comes just return as it is.

Upvotes: 2

Rumesh Krishnan
Rumesh Krishnan

Reputation: 443

you can use simple flatten.

scala> val a = Set(Array(1, 2),Array(8, 9))
//a: scala.collection.immutable.Set[Array[Int]] = Set(Array(1, 2), Array(8, 9))

scala> a.flatten
//res0: scala.collection.immutable.Set[Int] = Set(1, 2, 8, 9)

scala> a.map(x => x).flatten
//res9: scala.collection.immutable.Set[Int] = Set(1, 2, 8, 9)

Here, a.map(f) where f is A => B conversion function required. Other wise type mismatch.

Upvotes: 2

Related Questions