2

Given these case classes:

case class FeatureDistance(id: Long, distance: Double)

case class SearchResult(score: Float, id: Long)

Why does this not compile?

val distances = List[FeatureDistance](FeatureDistance(1L, 10f)) 
val results = distances.map(SearchResult(0f, _.id))

But this does:

val results = distances.map(fd => SearchResult(0f, fd.id))

The compilation error says: missing parameter type for expanded function ((x$3) => x$3.id)

Is it because _ is only scoped to the map function so it's not visible in the SearchResult.apply call?

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
  • I just encountered this the other day. I have no idea why it is that way, but I suspect it has to do with the scoping of the underscore character. Since it's really only just syntactic sugar, it shouldn't matter for your actual performance, though. – childofsoong Jul 16 '15 at 20:52

1 Answers1

1

After doing a bit of research, I found a post on the old scala forums that contains this quote:

When you use "_" as a place holder for an anonymous parameter of a function, the scope of that function is the innermost parenthesis containing it.

So, it's just a question of scope. I suspect this has to do with problems that could otherwise result from having nested function calls that use more than one underscore. For instance:

//suppose we have some x:List[List[Int]]
x.map(_.map(_ + 1))
childofsoong
  • 1,918
  • 16
  • 23
  • yeah that's what I thought, it's interesting though because we could do something like x.map(y => y.map(y => y + 1)) - although we would probably be shot for doing so! :D –  Jul 16 '15 at 21:05
  • That would be horrendous! – childofsoong Jul 16 '15 at 21:06