Recreate Kotlin String in literal format

Viewed 171

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.

1 Answers

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.

Related