Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: Line continuation in multiline string?

val myQuestion = """
I am creating a multiline string containing paragraphs of text.  The text will wrap when put into a TextView.  

But as you can see, when defining the text in the editor, if I want to avoid newlines mid-paragraph, I need to write really long lines that require a lot of horizontal scrolling.

Is there some way that I can have line breaks in the editor that don't appear in the actual value of the string?
"""
like image 759
Peter Avatar asked Mar 08 '26 19:03

Peter


1 Answers

Inspired by how you can add $ in a multiline string (which you otherwise cannot do) by doing ${"$"}, I've thought of this way of adding a line break in the multiline string literal, but not in the string value itself.

val myQuestion = """
    I am creating a multiline string containing paragraphs of text.  ${""
    }The text will wrap when put into a TextView.  

    But as you can see, when defining the text in the editor, ${""
    }if I want to avoid newlines mid-paragraph, I need to write ${""
    }really long lines that require a lot of horizontal scrolling.

    Is there some way that I can have line breaks in the editor ${""
    }that don't appear in the actual value of the string?
""".trimIndent()

(The indentation and trimIndent are just there to make it look nice. They are not required for this to work.)

Basically, I'm exploiting the fact that you can put arbitrary whitespace in ${ ... }, so how about putting a line break there? There still gotta be an expression in ${ ... } though, so you have to write "" to append nothing to the string.

like image 101
Sweeper Avatar answered Mar 11 '26 17:03

Sweeper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!