rampion rampion - 8 days ago 5x
Scala Question

Scala: How can I get an escaped representation of a string?

Basically, what I'd like to do is have:

// in foo.scala
val string = "this is a string\nover two lines"

Do this:

% scala foo.scala
this is a string
over two lines
"this is a string\nover two lines"

Basically looking for an analog of ruby's
or haskell's
show :: String -> String


This question is a bit old but I stumbled over it while searching for a solution myself and was dissatisfied with the other answers because they either are not safe (replacing stuff yourself) or require an external library.

I found a way to get the escaped representation of a string with the scala standard library (>2.10.0) which is safe. It uses a little trick:

Through runtime reflection you can can easily obtain a representation of a literal string expression. The tree of such an expression is returned as (almost) scala code when calling it's toString method. This especially means that the literal is represented the way it would be in code, i.e. escaped and double quoted.

def escape(raw: String): String = {
  import scala.reflect.runtime.universe._

The escape function therefore results in the desired code-representation of the provided raw string (including the surrounding double quotes):

scala> "\bHallo" + '\n' + "\tWelt"
res1: String =

scala> escape("\bHallo" + '\n' + "\tWelt")
res2: String = "\bHallo\n\tWelt"

This solution is admittedly abusing the reflection api but IMHO still safer and more maintainable than the other proposed solutions.