skip to content

Raw & Triple-Quoted Strings

Triple-quoted strings span lines and treat backslashes literally, which makes them the right tool for regexes, SQL, and JSON fixtures. The pair you should know is trimIndent() and trimMargin(), since raw strings otherwise carry your source indentation into the value.

part ofKotlinoverview, primer and where to startread it →
on this pageshow

questions

5

What is a triple-quoted (raw) string in Kotlin, and how does it differ from a regular double-quoted string?

level: juniorimportance: must knowfreq 55%

answer

  1. Three double quotes delimit it
  2. No escape processing — backslash is literal
  3. Spans multiple lines
  4. Templates $x / ${expr} still expand
  5. Literal $ via ${'$'}

basics

~10 s

A triple-quoted string is wrapped in three quotes. It can span many lines and treats backslashes as plain text, so you don't need escape codes like \n or \.

solid answer

~40 s

A raw string is delimited by three double-quote characters ("""..."""). Unlike a regular escaped string ("..."), it performs NO escape processing: a backslash is a literal backslash, so sequences like \n, \t, or \\ are kept verbatim rather than interpreted. It can also span multiple physical lines, with the line breaks preserved exactly in the resulting String. This makes raw strings ideal for regex patterns, file paths, JSON/SQL snippets, and any text full of backslashes. One thing that still works: string templates ($name and ${expr}) are expanded inside raw strings just as in regular strings. The only character you can't write literally is a sequence of three quotes; for that and for a literal $ you fall back to templates like ${'$'}.

code

kotlin · 6 lines
kotlin
val regex = Regex("""\d{3}-\d{4}""")   // \d stays literal, no \\d needed
val path  = """C:\temp\log.txt"""
val who   = "world"
val hi    = """Hi, $who\n"""            // ends with literal backslash-n, NOT a newline
println(regex.matches("123-4567"))      // true
println(hi.last())                       // 'n'

go deeper

for a junior

Knows the three-quote syntax, that it spans lines, and that backslashes are literal.

for a middle

Adds that templates still expand and knows the ${'$'} trick for a literal dollar.

for a senior

Frames the use cases (regex, paths, embedded DSL text) and mentions trimIndent/trimMargin for indentation hygiene.

for a principal

Discusses readability/maintainability trade-offs and when raw strings reduce escaping bugs versus when a resource file is better for large embedded text.

## What it is Kotlin has two String literal forms: - **Escaped (regular) string**: delimited by a single pair of double quotes, e.g. `"hello\nworld"`. The compiler interprets **escape sequences** — short backslash codes like `\n` (newline), `\t` (tab), `\\` (a single backslash), `\"` (a quote), `\u00e9` (a Unicode character). It cannot contain a raw line break. - **Raw / triple-quoted string**: delimited by three double quotes `"""..."""`. It performs **no escape processing at all** and **can span multiple lines**. ## No escape processing Inside a raw string, a backslash is just a backslash. So `"""C:\Users\me"""` is the eight-character path `C:\Users\me` with literal backslashes — no doubling needed. Likewise `\n` inside a raw string is the two characters backslash + n, **not** a newline. To get an actual newline you press Enter and write text on the next line. ```kotlin val regular = "line1\nline2" // escape \n -> real newline val raw = """line1 line2""" // real newline comes from the source line break println(regular == raw) // true: both hold the same two-line text val winPath = """C:\Users\name\file.txt""" // backslashes are literal ``` ## Templates still expand The one piece of processing that **does** happen is **string templates**. `$identifier` and `${expression}` are evaluated and substituted in raw strings exactly as in regular strings: ```kotlin val name = "Ada" val msg = """Hello, $name! Sum=${1 + 2}""" // Hello, Ada! Sum=3 ``` ## Edge cases - You cannot put a literal sequence of three quotes directly; and `$` always starts a template, so to write a literal dollar sign use `${'$'}` (a template whose value is the char `$`). - Raw strings often carry unwanted leading indentation from the source; `trimIndent()` and `trimMargin()` (extension functions on `String`) clean that up. ## When to use Regex (`Regex("""\d+""")`), Windows paths, embedded JSON/SQL/HTML, and multi-line templates — anywhere escaping would be noisy or error-prone.

  • How do you write a literal dollar sign inside a raw string?
    Use the template `${'$'}` — it inserts the Char '$'. A bare $ would be parsed as the start of a template reference.
  • Does `\n` create a newline in a raw string?
    No. Inside `"""..."""` the two characters backslash and n are kept literally. A real newline only comes from an actual line break in the source.

It's like a 'paste as plain text' box: whatever you type appears verbatim, except the app still fills in {{placeholders}}.

saying these in an interview costs you the question

  • Claiming \n works as a newline inside triple quotes
  • Saying templates do NOT expand in raw strings
  • Thinking raw strings are a different type than String
  • Confusing single-quote Char literals with triple-quote strings
  • Saying you must double backslashes in raw strings

context

open as a page

What does trimIndent() do to a multi-line raw string, and how does it decide how much to remove?

level: middleimportance: must knowfreq 50%

basics

~10 s

trimIndent() finds the common leading whitespace shared by all non-blank lines and removes that much from every line, so indented source code produces clean, left-aligned text.

open as a page

How does trimMargin() work, and when would you choose it over trimIndent()?

level: middleimportance: should knowfreq 38%

basics

~10 s

trimMargin() removes everything up to and including a marker character (a pipe | by default) at the start of each line. You mark where each line should begin, giving explicit control.

open as a page

Why are raw strings the preferred way to write regex patterns and Windows file paths in Kotlin? Show the difference.

level: seniorimportance: should knowfreq 33%

basics

~10 s

Regex and Windows paths contain many backslashes. In a normal string you must double each one, which is noisy and error-prone. Raw strings keep backslashes literal, so the pattern reads exactly as intended.

open as a page

Inside a raw string, how do you include a literal $ and a literal sequence of three double quotes, given templates still expand?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Templates run even in raw strings, so a bare $ before a name becomes a variable. Write a literal dollar with ${'$'}. Three quotes are hard to embed; use a template like ${"""""} to insert them.

open as a page