Re: Re: Strange type error
Andrew Phillips <[email protected]>
| Newsgroups | gmane.comp.lang.scala |
|---|---|
| Message-ID | <[email protected]> |
Hi Toby
> So, at the time the compiler needs to decide which part of the code
constitutes an anonymous function, it cannot
> yet take into account, what type is required. It needs to go by syntax
only, and that leaves few options besides
> limiting it to simple expressions.
Just to add to Oliver's answer: it's not explicitly stated in the spec
(6.23) in this way, but what works for me as a guideline is to regard the
scope of the anonymous function that the compiler creates as extending to
the *innermost enclosing expression* containing the '_' placeholder
character.
So _ + _* _ is desugared to (x, y, z) => x + y * z because the innermost
enclosing expression is the whole expression. In the case of _ + (_ * _),
however, the innermost enclosing expression for the latter two placeholders
is (_ * _), so the compiler first expands that to an anonymous function _ +
((y, z) => y * z) and then does that again for the first placeholder.
This also explains why e.g.
List(1, 2).map { i => println("Hi"); i + 1 } and
List(1, 2).map { println("Hi"); _ + 1 }
behave differently [1]: the innermost enclosing expression for the
placeholder in the second statement is _ + 1, so the result is effectively
List(1, 2).map { println("Hi"); i => i + 1 }
Regards
ap
[1] http://scalapuzzlers.com/#pzzlr-001
--
You received this message because you are subscribed to the Google Groups "scala-language" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [email protected].
For more options, visit https://groups.google.com/d/optout.