-2

I want a Scala string to be ${foo.bar} (literally, for testing some variable substitution later). I tried:

val str = "${foo.bar}"
val str = """${foo.bar}"""
val str = "\${foo.bar}"
val str = "$${foo.bar}"
val str = "$\{foo.bar}"

All giving compile errors like Error:(19, 15) possible missing interpolator: detected an interpolated expression or invalid escape character.

This is not a question about String interpolation (or variable substitution), This normally works without problems. Starting the Scala REPL (Scala 2.11.3, Java 1.8) works as expected. Somewhere there must be an SBT a setting (other than -Xlint or a hidden Xlint) which apparently is causing this behavior (from commandline and IntelliJ).

dr jerry
  • 9,768
  • 24
  • 79
  • 122
  • First two examples work fine for me ... The ones with backslash fail because `\$` and `\{` are indeed invalid. The `$$` works too (but produces two dollar signs). – Dima Sep 27 '18 at 11:25
  • Possible duplicate of [Scala String Interpolation with Underscore](https://stackoverflow.com/questions/50204130/scala-string-interpolation-with-underscore) – Raman Mishra Sep 27 '18 at 12:31

2 Answers2

4

The s or f interpolator will emit a constant:

$ scala -Xlint
Welcome to Scala 2.12.6 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_144).
Type in expressions for evaluation. Or try :help.

scala> "${foo.bar}"
<console>:12: warning: possible missing interpolator: detected an interpolated expression
       "${foo.bar}"
       ^
res0: String = ${foo.bar}

scala> f"$${foo.bar}"
res1: String = ${foo.bar}

It's usual to use -Xfatal-warnings to turn the warning into an error. IntelliJ reports it as an error at the source position, whereas scalac reports it as a warning, but with a summary error message that will fail a build.

som-snytt
  • 39,429
  • 2
  • 47
  • 129
  • The OP said it generated an error, whereas this only generates a warning and only if you turn those warnings on. I suspect that there is something else going on – Tim Sep 27 '18 at 12:55
  • I currently believe it's a battle against sbt settings (and possibly team policy). Thanks for your answer, this will help me further. – dr jerry Sep 27 '18 at 13:02
  • @Tim IntelliJ turns `-Xlint -Xfatal-warnings` into an error message as in OP. scalac will emit the warning and then a summary error message. So I think it's just IntelliJ config. But the source of the message is scalac's linter. – som-snytt Sep 28 '18 at 06:02
0

\$ and \{ are invalid escape characters and will not compile. The other versions compile just fine on 2.12.6 though perhaps there are problems in earlier versions.

Tim
  • 26,753
  • 2
  • 16
  • 29