2

I am trying to wrap my head around using underscore in function literals and the following has me stumped:

The following works:

def g(s: Int => Int) = 1.to(10).map(s(_))
g(_ * 2)

but this fails:

import scala.xml.Node
def f(s: Int => Node) = 1.to(10).map(s(_))
f(<p>{_}</p>)

The error being reported is:

Error:(11, 8) unbound placeholder parameter
f(<P>{_}</P>)
  ^

What explains this?

calvinkrishy
  • 3,798
  • 8
  • 30
  • 45

1 Answers1

2

It seems that you simply can't use a placeholder like this inside an XML literal.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
  • That seems arbitrary. Are there other types where underscore cannot be used like this? – calvinkrishy Sep 19 '14 at 16:19
  • Same situation happens in string interpolation. I am not certain, but it seems likely that the parser is looking for a complete expression inside braces (or after `$` in string interpolation), and `_` is not an expression by itself. – Alexey Romanov Sep 19 '14 at 16:32
  • Yeah, I noticed this SO answer talking about placeholders in String: http://stackoverflow.com/a/16688830/53949 – calvinkrishy Sep 19 '14 at 18:56