5

I am using the following code to meet my needs:

 (1 to 5)..map(i => s"\\x${i}")  // Produces List("\\x1", "\\x2", "\\x3", "\\x4", "\\x5")

But I would like to use a placeholder. According to the string interpolator documentation :

(1 to 5).map(s"\\x${_}")

should expand to:

(1 to 5).map(StringContext("\\\\x","").s(_))

But the latter works, not the former, which throws an error: unbound placeholder parameter on _. Why?

Mikaël Mayer
  • 10,425
  • 6
  • 64
  • 101

1 Answers1

11

I believe with the syntax:

(1 to 5).map(s"\\x${_}")

The compiler believes that the _ belongs to the s function in which case it won't work. You can easily solve this by doing something like this:

(1 to 5).map(i => s"\\x${i}")

You might want to have a look at this link for further clarity on the rules for placeholders in relation to anonymous functions.

EDIT: According to this post, the placeholder syntax used to work, so maybe this is a regression error or a feature that was never meant to work this way: https://groups.google.com/forum/#!msg/scala-internals/G_54LGj0zpg/REZfyXZ6-RwJ

Community
  • 1
  • 1
cmbaxter
  • 35,283
  • 4
  • 86
  • 95
  • I added the solution that I was already using directly in my question. I would like to have more than beliefs if possible. `s` is not a function, it is a scala feature. – Mikaël Mayer May 22 '13 at 10:03
  • 1
    @MikaëlMayer well, no, it's not a language feature. It's defined here: http://www.scala-lang.org/api/current/#scala.StringContext You can also use raw"", f"" or even create your own string interpolators (json"", sql"",...) – VasiliNovikov Mar 27 '14 at 14:41