xref: /aosp_15_r20/external/kotlinpoet/docs/n-for-names.md (revision 3c321d951dd070fb96f8ba59e952ffc3131379a0)
1%N for Names
2============
3
4Generated code is often self-referential. Use **`%N`** to refer to another generated declaration by
5its name. Here's a method that calls another:
6
7```kotlin
8fun byteToHex(b: Int): String {
9  val result = CharArray(2)
10  result[0] = hexDigit((b ushr 4) and 0xf)
11  result[1] = hexDigit(b and 0xf)
12  return String(result)
13}
14
15fun hexDigit(i: Int): Char {
16  return (if (i < 10) i + '0'.toInt() else i - 10 + 'a'.toInt()).toChar()
17}
18```
19
20When generating the code above, we pass the `hexDigit()` method as an argument to the `byteToHex()`
21method using `%N`:
22
23```kotlin
24val hexDigit = FunSpec.builder("hexDigit")
25  .addParameter("i", Int::class)
26  .returns(Char::class)
27  .addStatement("return (if (i < 10) i + '0'.toInt() else i - 10 + 'a'.toInt()).toChar()")
28  .build()
29
30val byteToHex = FunSpec.builder("byteToHex")
31  .addParameter("b", Int::class)
32  .returns(String::class)
33  .addStatement("val result = CharArray(2)")
34  .addStatement("result[0] = %N((b ushr 4) and 0xf)", hexDigit)
35  .addStatement("result[1] = %N(b and 0xf)", hexDigit)
36  .addStatement("return String(result)")
37  .build()
38```
39
40Another handy feature that `%N` provides is automatically escaping names that contain illegal
41identifier characters with double ticks. Suppose your code creates a `MemberName` with a Kotlin
42keyword as the simple name:
43
44```kotlin
45val taco = ClassName("com.squareup.tacos", "Taco")
46val packager = ClassName("com.squareup.tacos", "TacoPackager")
47val file = FileSpec.builder("com.example", "Test")
48  .addFunction(
49    FunSpec.builder("packageTacos")
50      .addParameter("tacos", LIST.parameterizedBy(taco))
51      .addParameter("packager", packager)
52      .addStatement("packager.%N(tacos)", packager.member("package"))
53      .build()
54  )
55  .build()
56```
57
58`%N` will escape the name for you, ensuring that the output will pass compilation:
59
60```kotlin
61package com.example
62
63import com.squareup.tacos.Taco
64import com.squareup.tacos.TacoPackager
65import kotlin.collections.List
66
67fun packageTacos(tacos: List<Taco>, packager: TacoPackager) {
68  packager.`package`(tacos)
69}
70```
71