Generated code
- Kotlin course
- Expert
- Lesson 11/47
- 5 min
Learn code generation with KSP.
Where does generated code go?
A KSP processor writes generated code via codeGenerator to build/generated/ksp/.... These files join the compilation.
Example: codeGenerator.createNewFile(...) opens a file, Kotlin source code is written to it, and it is closed. On the next compile this code is compiled like any source. This is how typed APIs are built without runtime reflection. Room's Dao implementation and Moshi's adapters are generated this way. You can inspect the generated code under the build folder.
A code generator example
A simple code generator takes a class name and produces a Kotlin source file for it. This is the text that KSP's codeGenerator will write.
Example: fun generateClass(name: String): String = "class $name(val id: Int)". If this function gets "User" it returns "class User(val id: Int)". In real KSP this text is written via codeGenerator.createNewFile(...). Here we focus on preparing the text itself. The generated text must be valid Kotlin; otherwise the next compile fails.
Practice Write generateClass
Define fun generateClass(name: String): String. It should return "class $name(val id: Int)". In main, print the results of generateClass("User") and generateClass("Order") on separate lines.
Starter code
// add the generateClass method
fun main() {
// generate and print for User and Order
}Sample solution
fun generateClass(name: String): String = "class $name(val id: Int)"
fun main() {
println(generateClass("User"))
println(generateClass("Order"))
}Expected output
class User(val id: Int) class Order(val id: Int)
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When is generated code compiled?
- At compile time, together with main sources Correct answer
- At runtime, when the app runs
- Only when tests run
- Never; it stays as a comment
Explanation: Generated code compiles in the same pass as main sources.
2 Complete the generateClass method
fun generateClass(name: String): String {
return "class ____(val id: Int)"
}
fun generateClass(name: String): String {
return "class $name(val id: Int)"
}
Explanation: $name makes each class name dynamic.
3 Match generation parts
| Term | Meaning |
|---|---|
codeGenerator |
File writing |
createNewFile |
Open new file |
build/generated |
Output folder |
generateClass |
Text generation |