Question

I heard in Scala I can use _ as "anonymous parameter" in anonymous function:

List(1,2,3).foreach(print(_))

But this code can't be compiled:

scala> def a[T](s: Seq[T]): Seq[T] = s.map(_)
<console>:7: error: missing parameter type for expanded function ((x$1) => s.map(x$1))

And this can:

scala> def a[T](s: Seq[T]): Seq[T] = s.map(x => x)
a: [T](s: Seq[T])Seq[T]

It seems about type inference. But how could x => x provide more information than _?

Was it helpful?

Solution

The problem here is not a type inference.

As you can see from error message equivalent code for s.map(_) is not s.map(x => x), but this:

i => s.map(i)

Just like print(_) (actually Predef.print(_)) means i => Predef.print(i).

Or like "a" + _ means "a".+(_) means s => "a".+(s).

This just doesn't make sense in current context.

Let's suppose you have a list of functions String => String (fs) and you want to apply all these functions to list of String. You'll use this code:

fs.map{f => s.map(f)}

or just this:

fs.map{s.map(_)}

Addition: you could use identity method instead if x => x. It's imported by default, but you could make it even shorter using addition import:

import Predef.{identity => id}
List(1, 2, 3) map id
// List[Int] = List(1, 2, 3)

Note that identity is a well known name, so in team you should use it instead of your aliases.

OTHER TIPS

It seems about type inference. But how could x => x provide more information than _?

x => x is a type of Function1, which is what the map function expects as parameter. The compiler can't infer that the anonymous variable _ of type T is really a Function1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top