Kotlin Academy · Lesson

Generating Kotlin Source Files with KotlinPoet

Use KotlinPoet inside a KSP processor to generate type-safe Kotlin code.

Lesson 3 of 414 steps

Generating Kotlin Source Files with KotlinPoet is a free Kotlin Academy lesson on CoddyKit. This is lesson 3 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, and your progress syncs across the web and the CoddyKit app. The Kotlin Academy course includes 4 lessons in total.

What Is KotlinPoet?

KotlinPoet is Square's Kotlin API for generating .kt source files programmatically. It produces well-formatted, idiomatic Kotlin code and integrates naturally with KSP's CodeGenerator.

Adding the Dependency

Add KotlinPoet to your processor module:

dependencies {
    implementation("com.squareup:kotlinpoet:1.17.0")
    implementation("com.squareup:kotlinpoet-ksp:1.17.0") // KSP extensions
}

FileSpec: The Root of a Generated File

FileSpec.builder(packageName, fileName) is the entry point. Add types, functions, and properties to it, then write the result through KSP's CodeGenerator:

val file = FileSpec.builder("com.example.generated", "MyFactory")
    .addType( /* TypeSpec here */ )
    .build()

TypeSpec: Defining a Class

Use TypeSpec.classBuilder() for classes, objectBuilder() for objects, and interfaceBuilder() for interfaces. Chain builder calls to add functions, properties, and superinterfaces:

val classSpec = TypeSpec.classBuilder("MyFactory")
    .addModifiers(KModifier.PUBLIC)
    .addFunction( /* FunSpec */ )
    .build()

FunSpec: Generating a Function

FunSpec.builder(name) creates a function. Use addParameter(), returns(), and addStatement() to build its signature and body:

val funSpec = FunSpec.builder("create")
    .addParameter("name", String::class)
    .returns(String::class)
    .addStatement("return "Hello, %L!", name")
    .build()

PropertySpec: Generating a Property

Use PropertySpec.builder(name, type) to generate properties. Specify KModifier.PRIVATE, KModifier.OVERRIDE, or use mutable() for var:

val propSpec = PropertySpec.builder("tag", String::class)
    .initializer("%S", "MyClass")
    .addModifiers(KModifier.PRIVATE)
    .build()

Code Format Specifiers

KotlinPoet uses format specifiers in addStatement() and initializer():

  • %L — literal (no quotes)
  • %S — string literal (with quotes)
  • %T — type name (handles imports automatically)
  • %N — name (of a spec or string)

Automatic Imports with %T

When you use %T with a ClassName, KotlinPoet automatically adds the required import. You never hand-write import statements:

val listType = ClassName("kotlin.collections", "List")
val funSpec = FunSpec.builder("items")
    .returns(listType.parameterizedBy(String::class.asTypeName()))
    .addStatement("return emptyList()")
    .build()

Writing to KSP CodeGenerator

Use the kotlinpoet-ksp bridge to write the generated FileSpec through KSP's CodeGenerator, preserving incremental build metadata:

file.writeTo(
    codeGenerator = codeGenerator,
    aggregating = false
)

Generating Extension Functions

Use FunSpec.builder(name).receiver(type) to generate extension functions:

val extFun = FunSpec.builder("toJson")
    .receiver(ClassName("com.example", "User"))
    .returns(String::class)
    .addStatement("return Gson().toJson(this)")
    .build()

Practical Use Case: Factory Generator

A KSP processor annotates data classes with @AutoFactory and uses KotlinPoet to generate a companion-factory object for each one. The generated file is placed in the same package as the original class.

Testing Generated Code

Use KotlinPoet's FileSpec.toString() in unit tests to assert on the generated source text without writing to disk. The kotlin-compile-testing-ksp library can compile and execute generated code in tests.

Quick Check

In KotlinPoet, which format specifier automatically adds the necessary import for a referenced class?

Recap: Generating Kotlin Source Files with KotlinPoet

Key takeaways:

  • FileSpec → top-level file; TypeSpec → class/object/interface; FunSpec → function; PropertySpec → property
  • Use %T for type references — imports are automatic
  • Write via file.writeTo(codeGenerator) in KSP processors
  • Use FileSpec.toString() for unit testing generated output
Free to start

Learn Kotlin with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
51
Lessons
203

Frequently Asked Questions

Is the “Generating Kotlin Source Files with KotlinPoet” lesson free?

Yes — any 3 lessons of the Kotlin Academy learning path, including “Generating Kotlin Source Files with KotlinPoet”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Kotlin Academy course includes 4 lessons in total.

What will I learn in “Generating Kotlin Source Files with KotlinPoet”?

Use KotlinPoet inside a KSP processor to generate type-safe Kotlin code. You practise Kotlin Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Kotlin Academy?

No prior experience is required. Kotlin Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.

How long does the “Generating Kotlin Source Files with KotlinPoet” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Kotlin Academy lesson?

Yes. Every Kotlin Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. KSP vs KAPT: Why KSP Is Faster
  2. Writing Your First SymbolProcessor
  3. Generating Kotlin Source Files with KotlinPoet
  4. Integrating KSP Processors into a Gradle Build
← Back to Kotlin Academy