Multi-dollar string interpolation

suggest change

In a Kotlin string, $ starts a template: $name inserts a variable and ${expr} inserts an expression (see String Templates). That's handy until the text you're writing uses $ itself. JSON Schema has $schema and $ref, GraphQL has $id variables, MongoDB has $match and $sum, and shell scripts, Makefiles and regex replacements are full of $.

Kotlin 2.2 added multi-dollar interpolation. Put one or more $ in front of a string literal and that number of dollars becomes the interpolation trigger:

$$"price: $9.99, item: $$name"           // $ is literal, $$name interpolates
$$"""{"$schema": "...", "id": "$$id"}"""  // works for raw strings too

Versions:

All the examples below were compiled with Kotlin 2.4.21 on JDK 25.

The problem it solves

Before 2.2 there were two ways to write a literal $ that comes before a name:

Here is the same JSON written all three ways:

fun main() {
    val type = "string"

    // escaped string: escape every literal $ with a backslash
    val a = "{\"\$schema\": \"https://json-schema.org/draft/2020-12/schema\", \"type\": \"$type\"}"

    // raw string: no escapes, so the old trick is ${'$'}
    val b = """{"${'$'}schema": "https://json-schema.org/draft/2020-12/schema", "type": "$type"}"""

    // multi-dollar raw string: $ is literal, $$ interpolates
    val c = $$"""{"$schema": "https://json-schema.org/draft/2020-12/schema", "type": "$$type"}"""

    println(c)
    println(a == b && b == c)
}

Output:

{"$schema": "https://json-schema.org/draft/2020-12/schema", "type": "string"}
true

The first two work, but they're hard to read, and it gets worse when a template has dozens of $. You also can't paste a JSON Schema or GraphQL query from the docs into the code without editing it. With $$""" you paste it as is and mark only the parts that come from Kotlin.

The rules

The number of $ before the opening quote is the interpolation prefix. Inside the string:

fun main() {
    val user = "ana"
    val items = listOf(3, 4)

    println($$"$user")                  // one $: literal text
    println($$"$$user")                 // two $: interpolation
    println($$"$${items.sum()} items")  // two $ and braces: expression
    println($$"${items.sum()}")         // one $ and braces: literal text
    println($$"$$$user")                // literal $, then $$user
    println($$"$ $$ $5 $$5 $")          // not followed by a name or {: literal
}

Output:

$user
ana
7 items
${items.sum()}
$ana
$ $$ $5 $$5 $

The last line shows that a run of $ that isn't followed by a name or { is always literal, whatever its length. That was already true for ordinary strings: "$9.99" and "^\\d+$" never needed escaping, because 9 and " can't start a name.

Other things to know:

fun main() {
    val total = 42
    println($$"Total: $$total, the template engine sees: ${total}")
    println($$"tab:\t|, quote: \", dollar: \$")
    println($$"""
        |raw strings keep \t and \$ as typed
        |total = $$total
    """.trimMargin())
}

Output:

Total: 42, the template engine sees: ${total}
tab:	|, quote: ", dollar: $
raw strings keep \t and \$ as typed
total = 42

trimIndent() and trimMargin() work as usual (see String Literals), because the prefix only changes how the literal is parsed. The result is an ordinary String.

JSON Schema

JSON Schema keywords start with $: $schema, $id, $ref, $defs, $comment. With a $$ raw string the schema looks exactly like the JSON, and only the values that come from Kotlin use $$:

import kotlinx.serialization.json.*

data class Field(val name: String, val type: String, val description: String)

fun schema(id: String, title: String, fields: List<Field>): String {
    val properties = fields.joinToString(",\n") { f ->
        $$"""    "$${f.name}": { "$ref": "#/$defs/$${f.type}", "description": "$${f.description}" }"""
    }
    return $$"""
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://example.com/schemas/$$id.json",
  "title": "$$title",
  "type": "object",
  "properties": {
$$properties
  },
  "required": [$${fields.joinToString { "\"${it.name}\"" }}],
  "$defs": {
    "email": { "type": "string", "format": "email" },
    "positiveInt": { "type": "integer", "minimum": 1 }
  }
}
""".trim()
}

fun main() {
    val text = schema(
        id = "user",
        title = "User",
        fields = listOf(
            Field("email", "email", "Login address"),
            Field("age", "positiveInt", "Age in years"),
        ),
    )
    println(text)

    // check that the result is valid JSON and read keys that start with $
    val json = Json.parseToJsonElement(text).jsonObject
    println(json[$$"$id"])
    println(json[$$"$defs"]!!.jsonObject.keys)
}

Output:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://example.com/schemas/user.json",
  "title": "User",
  "type": "object",
  "properties": {
    "email": { "$ref": "#/$defs/email", "description": "Login address" },
    "age": { "$ref": "#/$defs/positiveInt", "description": "Age in years" }
  },
  "required": ["email", "age"],
  "$defs": {
    "email": { "type": "string", "format": "email" },
    "positiveInt": { "type": "integer", "minimum": 1 }
  }
}
"https://example.com/schemas/user.json"
[email, positiveInt]

The example uses kotlinx-serialization-json 1.11.0 (see JSON) only to check the output. Note the nested "\"${it.name}\"" inside $${ ... }: it's a normal string, so it uses a single $.

Building JSON by gluing strings together doesn't escape values. If a value can contain " or \, build the document with buildJsonObject or a serializer instead and use multi-dollar strings for fixed parts and keys.

Keys in annotations and constants

A $$ literal with no interpolation is a compile-time constant, so you can use it in const val and in annotation arguments. That's handy for property names like $schema in kotlinx.serialization:

import kotlinx.serialization.*
import kotlinx.serialization.json.*

const val SCHEMA_KEY = $$"$schema"

@Serializable
data class Config(
    @SerialName($$"$schema") val schema: String,
    val name: String,
    @SerialName($$"$comment") val comment: String? = null,
)

fun main() {
    val cfg = Config("https://example.com/config.schema.json", "demo")
    val text = Json.encodeToString(cfg)
    println(text)
    println(Json.decodeFromString<Config>(text).schema == cfg.schema)
    println(SCHEMA_KEY.length)
}

Output:

{"$schema":"https://example.com/config.schema.json","name":"demo"}
true
7

Before, this was written @SerialName("\$schema").

GraphQL queries

GraphQL variables are written $name. A query can be copied from a GraphQL explorer straight into a $$""" string, and Kotlin values can still be inserted with $$:

import kotlinx.serialization.json.*

fun userQuery(fields: List<String>): String = $$"""
    query User($id: ID!, $first: Int = 10) {
      user(id: $id) {
        $${fields.joinToString(" ")}
        posts(first: $first) { title }
      }
    }
""".trimIndent()

fun main() {
    val query = userQuery(listOf("id", "name", "email"))
    println(query)

    val body = buildJsonObject {
        put("query", query)
        putJsonObject("variables") {
            put("id", "u-17")
            put("first", 3)
        }
    }
    println(body["variables"])
}

Output:

query User($id: ID!, $first: Int = 10) {
  user(id: $id) {
    id name email
    posts(first: $first) { title }
  }
}
{"id":"u-17","first":3}

Pass user input through GraphQL variables, as shown, and not by interpolating it into the query text. Interpolation is fine for parts you control, like the list of fields.

MongoDB queries

MongoDB operators ($match, $gte, $group, $sum) and field paths ("$amount") all start with $. An aggregation pipeline written as JSON text, for a shell script, a test fixture or a driver's Document.parse, stays readable:

fun mongoFilter(customer: String, minAmount: Int): String = $$"""
    [
      { "$match": { "customer": "$$customer", "amount": { "$gte": $$minAmount } } },
      { "$group": { "_id": "$status", "total": { "$sum": "$amount" } } },
      { "$sort": { "total": -1 } }
    ]
""".trimIndent()

fun main() {
    println(mongoFilter("acme", 100))
}

Output:

[
  { "$match": { "customer": "acme", "amount": { "$gte": 100 } } },
  { "$group": { "_id": "$status", "total": { "$sum": "$amount" } } },
  { "$sort": { "total": -1 } }
]

As with JSON Schema, string interpolation doesn't escape anything. For real queries with user-supplied values, use the driver's builders.

Regex replacement strings

In a Java/Kotlin regex replacement, $1 refers to a numbered group and ${name} to a named group. $1 never needed escaping, because a name can't start with a digit, but ${name} collides with Kotlin's expression syntax:

fun main() {
    val date = Regex("""(?<year>\d{4})-(?<month>\d\d)-(?<day>\d\d)""")
    val sep = "/"

    // ${name} in a replacement string is a reference to a named group
    val old = date.replace("due 2026-10-18", "\${day}$sep\${month}$sep\${year}")
    val new = date.replace("due 2026-10-18", $$"${day}$$sep${month}$$sep${year}")
    println(old)
    println(new)

    // numbered groups and the end anchor never needed escaping
    println(Regex("""(\w+)@(\w+)$""").replace("mail ana@example", "$2 <- $1"))
}

Output:

due 18/10/2026
due 18/10/2026
mail example <- ana

In the $$ version, ${day} goes to the regex engine and $$sep is the Kotlin variable. More about regex is in Introduction to regular expressions in Kotlin.

When text contains $$: use three dollars

Some formats use $$ themselves. In a Makefile, $(CC) is a make variable and $$f is an escaped dollar that reaches the shell as $f. In a $$ Kotlin string, $$f would be read as the Kotlin variable f. Pick a prefix longer than any run of $ before a name in the text, here $$$:

fun makefile(target: String, sources: List<String>): String = $$$"""
    CC ?= cc
    SRCS = $$${sources.joinToString(" ")}

    $$$target: $(SRCS:.c=.o)
    	$(CC) -o $@ $^

    check:
    	for f in $(SRCS); do test -f $$f || echo "missing $$f"; done
""".trimIndent()

fun main() {
    println(makefile("app", listOf("main.c", "util.c")))
}

Output:

CC ?= cc
SRCS = main.c util.c

app: $(SRCS:.c=.o)
	$(CC) -o $@ $^

check:
	for f in $(SRCS); do test -f $$f || echo "missing $$f"; done

The recipe lines start with a real tab character, which make requires. trimIndent() removes the 4 spaces of common indentation and leaves the tab.

You can use as many dollars as you need ($$$$$"..." compiles), but 2 covers almost everything and 3 covers the rest.

Generating code with templates

Code generators, such as annotation processors, KSP processors or Gradle tasks that write source files, often produce code that has its own string templates. Generating Kotlin from Kotlin is the classic case:

fun dataClass(name: String, props: List<Pair<String, String>>): String {
    val params = props.joinToString { (n, t) -> "val $n: $t" }
    val fields = props.joinToString { (n, _) -> $$"$$n=$$$n" }
    return $$"""
        data class $$name($$params) {
            override fun toString() = "$$name($$fields)"
            fun describe() = "${this::class.simpleName} with $${props.size} properties"
        }
    """.trimIndent()
}

fun main() {
    println(dataClass("User", listOf("id" to "Int", "name" to "String")))
}

Output:

data class User(val id: Int, val name: String) {
    override fun toString() = "User(id=$id, name=$name)"
    fun describe() = "${this::class.simpleName} with 2 properties"
}

$$"$$n=$$$n" uses all three rules at once: $$n inserts the property name, and $$$n is a literal $ followed by the name again, which gives id=$id. The generated class compiles and prints User(id=1, name=Ana). The same approach works for generating shell scripts, PHP, Groovy or Gradle build files. For bigger templates, see Text and HTML templates.

A bug the prefix prevents

In an ordinary string, a $ you meant as text may compile anyway. If there's no variable with that name, you get an error such as error: unresolved reference 'ref'. If there is one, the string silently changes:

fun main() {
    val schema = "v2"
    println("{\"$schema\": \"...\"}")   // oops: interpolates the variable
    println($$"{\"$schema\": \"...\"}") // literal $schema
}

Output:

{"v2": "..."}
{"$schema": "..."}

In a $$ string a single $ is always text, so adding or renaming a local variable can't change the output.

Older language versions

The syntax needs language version 2.2. If a project still sets -language-version 2.1 (or languageVersion in Gradle's compilerOptions), Kotlin 2.4 rejects it:

warning: language version 2.1 is deprecated and its support will be removed in a future version of Kotlin. Update the version to 2.2.
t5.kt:3:13: error: the feature "multi dollar interpolation" is only available since language version 2.2
    println($$"abc")
            ^^^^^^^

Libraries that must compile with Kotlin 2.1 or older have to keep using \$ and ${'$'}.

Summary

You want Ordinary string $$ string
literal $name "\$name" or "${'$'}name" $$"$name"
literal ${x} "\${x}" $$"${x}"
insert a variable "$name" $$"$$name"
insert an expression "${a + b}" $$"$${a + b}"
literal $ before a value "\$$price" $$"$$$price"
text that has $$name "\$\$name" use $$$"$$name"

Use a multi-dollar string whenever the text has more than one or two literal $: JSON Schema, GraphQL, MongoDB, shell, Makefiles, regex replacements and generated code. Choose a prefix longer than the longest run of $ before a name in the text.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents