3

Given a string in Kotlin, how can I print it in what would be a string literal format?

Or in longer form, given some method named foo that does this, it would do the following:

println("Howdy".foo()) --> "Howdy" (quotes included in the output)
println("1 line\n\tand a tab".foo()) --> "1 line\n\tand a tab"
println("\"embeded quotes\"".foo()) --> "\"embeded quotes\""

Basically I'm trying to create debug output that matches the code form of the string. toString just returns the string, not the dressing/escaping to recreate it in code.

Travis Griggs
  • 21,522
  • 19
  • 91
  • 167
  • If you're using Kotlin JVM, take a look at the [Java version of this question](https://stackoverflow.com/questions/1350397/java-equivalent-of-python-repr), you should be able to use any of those solutions just as easily in Kotlin JVM thanks to Kotlin-Java interop – Kevin K Dec 16 '20 at 01:34

1 Answers1

5

It seems like the developers aren't particularly keen on adding the feature into the language directly, but you can always do it yourself:

fun escapeChar(c: Char): String =
    when (c) {
        '\t' -> "\\t"
        '\b' -> "\\b"
        '\n' -> "\\n"
        '\r' -> "\\r"
        '"' -> "\\\""
        '\\' -> "\\\\"
        '\$' -> "\\\$"
        in ' '..'~' -> c.toString()
        else -> "\\u" + c.toInt().toString(16).padStart(4, '0')
    }

fun String.escape()
    = "\"${this.map(::escapeChar).joinToString("")}\""

Note that this implementation errs on the side of leniency, so all non-ascii characters will be encoded in a unicode escape.

Aplet123
  • 33,825
  • 1
  • 29
  • 55