xref: /aosp_15_r20/external/kotlinpoet/docs/code-block-format-strings.md (revision 3c321d951dd070fb96f8ba59e952ffc3131379a0)
1Code Block Format Strings
2=========================
3
4Code blocks may specify the values for their placeholders in a few ways. Only one style may be used
5for each operation on a code block.
6
7## Relative Arguments
8
9Pass an argument value for each placeholder in the format string to `CodeBlock.add()`. In each
10example, we generate code to say "I ate 3 tacos"
11
12```kotlin
13CodeBlock.builder().add("I ate %L %L", 3, "tacos")
14```
15
16## Positional Arguments
17
18Place an integer index (1-based) before the placeholder in the format string to specify which
19argument to use.
20
21```kotlin
22CodeBlock.builder().add("I ate %2L %1L", "tacos", 3)
23```
24
25## Named Arguments
26
27Use the syntax `%argumentName:X` where `X` is the format character and call `CodeBlock.addNamed()`
28with a map containing all argument keys in the format string. Argument names use characters in
29`a-z`, `A-Z`, `0-9`, and `_`, and must start with a lowercase character.
30
31```kotlin
32val map = LinkedHashMap<String, Any>()
33map += "food" to "tacos"
34map += "count" to 3
35CodeBlock.builder().addNamed("I ate %count:L %food:L", map)
36```
37