xref: /aosp_15_r20/external/kotlinpoet/docs/p-for-string-templates.md (revision 3c321d951dd070fb96f8ba59e952ffc3131379a0)
1%P for String Templates
2=======================
3
4`%S` also handles the escaping of dollar signs (`$`), to avoid inadvertent creation of string
5templates, which may fail to compile in generated code:
6
7```kotlin
8val stringWithADollar = "Your total is " + "$" + "50"
9val funSpec = FunSpec.builder("printTotal")
10  .returns(String::class)
11  .addStatement("return %S", stringWithADollar)
12  .build()
13```
14
15produces:
16
17```kotlin
18fun printTotal(): String = "Your total is ${'$'}50"
19```
20
21If you need to generate string templates, use `%P`, which doesn't escape dollars:
22
23```kotlin
24val amount = 50
25val stringWithADollar = "Your total is " + "$" + "amount"
26val funSpec = FunSpec.builder("printTotal")
27  .returns(String::class)
28  .addStatement("return %P", stringWithADollar)
29  .build()
30```
31
32produces:
33
34```kotlin
35fun printTotal(): String = "Your total is $amount"
36```
37
38You can also use `CodeBlock`s as arguments to `%P`, which is handy when you need to reference
39importable types or members inside the string template:
40
41```kotlin
42val file = FileSpec.builder("com.example", "Digits")
43  .addFunction(
44    FunSpec.builder("print")
45      .addParameter("digits", IntArray::class)
46      .addStatement("println(%P)", buildCodeBlock {
47        val contentToString = MemberName("kotlin.collections", "contentToString")
48        add("These are the digits: \${digits.%M()}", contentToString)
49      })
50      .build()
51  )
52  .build()
53println(file)
54```
55
56The snippet above will produce the following output, handling the imports properly:
57
58```kotlin
59package com.example
60
61import kotlin.IntArray
62import kotlin.collections.contentToString
63
64fun print(digits: IntArray) {
65  println("""These are the digits: ${digits.contentToString()}""")
66}
67```
68