142

How do I escape a dollar sign in string interpolation?

def getCompanion(name: String) = Class.forName(s"my.package.$name\$")

// --> "error: unclosed string literal"
0__
  • 66,707
  • 21
  • 171
  • 266

1 Answers1

212

Just double it

scala> val name = "foo"
name: String = foo

scala> s"my.package.$name$$"
res0: String = my.package.foo$
4e6
  • 10,696
  • 4
  • 52
  • 62
  • 5
    Would love to see a link to some documentation on this one. There might be other cases than the exact one here, and the answer could then help more people – Martin Hallén Jan 18 '18 at 11:00
  • I can not find anything about this in the documentation. There is a PR to add it though: https://github.com/scala/docs.scala-lang/pull/1531 – amoebe Sep 25 '19 at 17:12
  • 1
    The documentation is now here: https://docs.scala-lang.org/overviews/core/string-interpolation.html#the-s-string-interpolator Nor sure what other cases there are? – amoebe Oct 07 '19 at 16:25
  • I can confirm this works for the percentage sign (`%`) as well, because it breaks if used after a numerical value in the f-string. – Lucas Lima Aug 18 '22 at 14:18