CodeBlanks Logo Icon CodeBlanks

KSP

Write code generation with KSP.

Code generation with KSP

The third lesson represents code generation with KSP (Kotlin Symbol Processing). KSP reads annotations at compile time and generates code.

In our model the @AutoBuilder annotation marks a class; KSP generates a builder for it. In this lesson we model the concept by writing the builder by hand: annotation class AutoBuilder and class NoteBuilder. The builder creates a Note step by step. This is the hand-written version of the real KSP flow.

The NoteBuilder model

NoteBuilder is the hand-written version of the builder KSP would generate. var fields are filled step by step; the build() method produces the final Note.

Example: class NoteBuilder { var id = 0; var title = ""; fun build(): Note = Note(id, title) }. Usage: val b = NoteBuilder(); b.title = "KSP"; b.build(). This is the basis of the fluent builder pattern. Real KSP generates this class automatically; we wrote it by hand as a model.

Practice Add AutoBuilder and NoteBuilder

Define annotation class AutoBuilder. Define class NoteBuilder with var id = 0, var title = "", fun build(): Note = Note(id, title). In main, do val b = NoteBuilder(); b.title = "KSP" and write println(b.build().title).

Starter code

Main.kt
object App {
    fun run(): String = "Expert Notes"
}

data class Note(val id: Int, val title: String)

// add the @AutoBuilder annotation and NoteBuilder class

fun main() {
    // build a Note with NoteBuilder and print it
}

Sample solution

Main.kt
object App {
    fun run(): String = "Expert Notes"
}

data class Note(val id: Int, val title: String)

annotation class AutoBuilder

class NoteBuilder {
    var id = 0
    var title = ""
    fun build(): Note = Note(id, title)
}

fun main() {
    val b = NoteBuilder()
    b.title = "KSP"
    println(b.build().title)
}

Expected output

KSP

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When does KSP run?

Main.kt
KSP runs during compilation.
  • Runtime
  • Load time
  • Compile time Correct answer
  • Shutdown

Explanation: KSP processes annotations at compile time.

2 Complete the annotation declaration

Question
annotation class ____
Answer
annotation class AutoBuilder

Explanation: annotation class AutoBuilder marks a class.

3 Match the KSP parts

Term Meaning
KSP Symbol processing
@AutoBuilder Marker
NoteBuilder Builder model
build() Build method

All lessons in Expert