Search code examples
kotlincode-generationstring-literalskotlinpoet

With KotlinPoet or similar; generating a non-raw Kotlin string literal


Straightforward; is there a way to generate a valid Kotlin string literal (non-raw, as in non-triple-quote) from a string; I'm currently trying to accomplish this with KotlinPoet.

For clarity sake, example input:

Hello, how are you?
I'm doing "great"!
I hope you are too!
It'll cost you $2.

Desired example output:

"Hello, how are you?\nI'm doing \"great\"!\nI hope you are too!\nIt'll cost you \$2."

With KotlinPoet, the best I can manage from the API I've learned thus far is:

"""
|Hello, how are you?
|I'm doing "great"!
|I hope you are too!
|It'll cost you ${'$'}2.
|""".trimMargin()

Which, while functional, is not what I'm trying to achieve.


I've been able to accomplish something functionally close, with Jackson's ObjectMapper::writeValueAsString, however, I'm sure there's plenty of caveats with using this to generate valid Kotlin code.


Solution

  • Unfortunately, the relevant function in KotlinPoet is internal, or you could just call it with isConstantContext = true as in this test.

    So as a workaround, you can put the string in a constant context, such as const val x = ... or @A(...) (where ... is your string), generate code for it and then remove everything but the literal.