-1

Here's my code.

def f(x: Int) = x
val a = List(List(1), List(2, 2))

val b = a map { f(_.length) } // error
val c = a map { item => f(item.length) } // no error

Error occurs when compute b, it seems like the compiler expands the code in the following way:

val b = a map { f(x => x.length) } // absolutely wrong

That's why there's an error. And the correct expandation is something similar to what I do when compute c. However, how can compiler expand a function for f when function f doesn't expect a function?

For me, this expandation doesn't make any sense. Can anyone explain this behavior? Thanks!

  • 1
    It expands as expected. Its just that your expectations are not right. If you consider the to compare the whole thing to pattern matching... you should be able to see what went wrong. Although... its not exactly correct... for the purpose of understanding, just think of a `.map(_.length)` to be similar to this this `map(x => x match { case _ => x.length })`. Now what you have written is `a.map(f(x => x match { case _ => x.length }))` – sarveshseri Oct 04 '16 at 06:40
  • @Micho I disagree that it's a duplicate of that question. The answers there only say _how_ the placeholder syntax is expanded, but the question author already knows that. – Alexey Romanov Oct 04 '16 at 06:55
  • @SarveshKumarSingh Thx! Your example really help me :) – Chujie Zeng Oct 05 '16 at 05:47

1 Answers1

0

However, how can compiler expand a function for f when function f doesn't expect a function?

Because this expansion happens before typing: the compiler doesn't know what f expects yet. This is a good thing because 1) when reading the code you also don't need to know whether f expects a function to understand how it will expand; 2) changing the type of f doesn't radically change the meaning of code.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487