Search code examples
kotlinmultiline

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?
"""

Solution

  • Another approach is to treat a single-newline as an "editor only" newline, which gets removed. If you actually want a single-newline put a double-newline. If you want a double, put a triple, and so-on:

    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().replace(Regex("(\n*)\n"), "$1")
    

    This is similar to the approach of Markdown - which ignores lone newlines (unless the previous line ends with 2 or more spaces - which I find confusing).