Raw Strings

We'll cover the following

Dealing with escape characters makes the code messy. Instead of using escaped strings, in Kotlin we may use raw strings which start and end with three double quotes. We may use raw strings to place any character, without the need to use escapes, and may also use them to create multiline strings.

No escape

In an escaped string which starts and ends with a single double quote, we can’t place a variety of characters, like new line or a double quote, for example, without using the escape character \. Even a simple case can be unpleasant to read, like this one:

val escaped = "The kid asked, \"How's it going, $name?\""

We had to escape the double quotes that were needed within the string. The more we use escaped strings, the messier it becomes. Instead of using escaped strings, in Kotlin we use raw strings. Just like escaped strings, raw strings can also be used as string templates, but without the mess of escaping characters. Here’s the above escaped string changed to raw string—less clutter, more readable:

val raw = """The kid asked, "How's it going, $name?""""

Use escaped string, ironically, when you don’t need to escape anything—for small, simple, plain vanilla strings. If you need anything more complex or multiple lines of string, then reach over to raw strings.

Multiline strings

The infamous + operator is often used to create multiple lines of strings, and that leads to nasty code that’s hard to maintain. Kotlin removes that ceremony with a multiline string, which is a raw string that contains line breaks. Multiline strings can also act as string templates.

Let’s create a string that runs across several lines, but without the + operator.

Get hands-on with 1400+ tech skills courses.