xref: /aosp_15_r20/external/kotlinpoet/docs/s-for-strings.md (revision 3c321d951dd070fb96f8ba59e952ffc3131379a0)
1%S for Strings
2==============
3
4When emitting code that includes string literals, we can use **`%S`** to emit a **string**, complete
5with wrapping quotation marks and escaping. Here's a program that emits 3 methods, each of which
6returns its own name:
7
8```kotlin
9fun main(args: Array<String>) {
10  val helloWorld = TypeSpec.classBuilder("HelloWorld")
11    .addFunction(whatsMyNameYo("slimShady"))
12    .addFunction(whatsMyNameYo("eminem"))
13    .addFunction(whatsMyNameYo("marshallMathers"))
14    .build()
15
16  val kotlinFile = FileSpec.builder("com.example.helloworld", "HelloWorld")
17    .addType(helloWorld)
18    .build()
19
20  kotlinFile.writeTo(System.out)
21}
22
23private fun whatsMyNameYo(name: String): FunSpec {
24  return FunSpec.builder(name)
25    .returns(String::class)
26    .addStatement("return %S", name)
27    .build()
28}
29```
30
31In this case, using `%S` gives us quotation marks:
32
33```kotlin
34class HelloWorld {
35  fun slimShady(): String = "slimShady"
36
37  fun eminem(): String = "eminem"
38
39  fun marshallMathers(): String = "marshallMathers"
40}
41```
42