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.

1
  • If you're using Kotlin JVM, take a look at the Java version of this question, you should be able to use any of those solutions just as easily in Kotlin JVM thanks to Kotlin-Java interop Commented Dec 16, 2020 at 1:34

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.