or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

annotations-and-metadata.mdcode-generation.mdfile-and-type-generation.mdfunction-and-property-generation.mdindex.mdtype-system.mdutilities.md
tile.json

tessl/maven-com-squareup--kotlinpoet

Kotlin and Java API for generating Kotlin source files (.kt) with type-safe, fluent builder patterns

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
mavenpkg:maven/com.squareup/kotlinpoet@2.2.x

To install, run

npx @tessl/cli install tessl/maven-com-squareup--kotlinpoet@2.2.0

index.mddocs/

KotlinPoet

KotlinPoet is a comprehensive Kotlin and Java API for generating Kotlin source files (.kt) programmatically. It provides type-safe, fluent builder patterns for creating well-formatted Kotlin code, supporting all modern Kotlin language constructs including classes, functions, properties, type aliases, and annotations. As a multiplatform library supporting JVM, JavaScript, and WebAssembly targets, KotlinPoet is the go-to solution for code generation in build tools, annotation processors, and development utilities.

Package Information

  • Package Name: kotlinpoet
  • Package Type: maven
  • Language: Kotlin (Multiplatform: JVM, JS, WebAssembly)
  • Installation:
    • Gradle: implementation("com.squareup:kotlinpoet:2.2.0")
    • Maven:
      <dependency>
        <groupId>com.squareup</groupId>
        <artifactId>kotlinpoet</artifactId>
        <version>2.2.0</version>
      </dependency>

Core Imports

import com.squareup.kotlinpoet.*

Common specific imports:

import com.squareup.kotlinpoet.FileSpec
import com.squareup.kotlinpoet.TypeSpec
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.PropertySpec
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.CodeBlock

For JVM-specific annotations:

import com.squareup.kotlinpoet.jvm.JvmAnnotations

Basic Usage

import com.squareup.kotlinpoet.*

// Create a simple class with a function
val greeterClass = TypeSpec.classBuilder("Greeter")
    .addProperty(
        PropertySpec.builder("name", String::class)
            .initializer("%S", "World")
            .build()
    )
    .addFunction(
        FunSpec.builder("greet")
            .returns(String::class)
            .addStatement("return %S + name", "Hello, ")
            .build()
    )
    .build()

// Create a file containing the class
val file = FileSpec.builder("com.example", "Greeter")
    .addType(greeterClass)
    .build()

// Output the generated code
file.writeTo(System.out)

/* Generated output:
package com.example

import kotlin.String

class Greeter {
  val name: String = "World"

  fun greet(): String = "Hello, " + name
}
*/

Architecture

KotlinPoet is built around several key architectural components:

  • Specification Builders: Core classes (FileSpec, TypeSpec, FunSpec, PropertySpec) using the Builder pattern for constructing code elements
  • Type System: Complete representation of Kotlin's type system (TypeName, ClassName, ParameterizedTypeName) with nullability and annotation support
  • Code Generation: CodeBlock for template-based code fragment generation with placeholder substitution
  • Multiplatform Design: Common API with platform-specific implementations for JVM, JS, and WebAssembly
  • Utility Layer: NameAllocator for identifier management, KModifier/KOperator enums for language constructs

Capabilities

File and Type Generation

Core functionality for creating Kotlin files and type declarations including classes, interfaces, objects, and annotation classes. This forms the foundation of all code generation workflows.

// File specification
class FileSpec private constructor() {
    companion object {
        fun builder(packageName: String, fileName: String): Builder
        fun builder(className: ClassName): Builder
        fun builder(memberName: MemberName): Builder
        fun get(packageName: String, typeSpec: TypeSpec): FileSpec
        fun scriptBuilder(fileName: String, packageName: String = ""): Builder
    }
    fun writeTo(out: Appendable)
    fun writeTo(directory: Path)
    fun toJavaFileObject(): JavaFileObject
    fun toBuilder(packageName: String = this.packageName, name: String = this.name): Builder
}

// Type specification  
class TypeSpec private constructor() {
    companion object {
        fun classBuilder(name: String): Builder
        fun classBuilder(className: ClassName): Builder
        fun interfaceBuilder(name: String): Builder
        fun interfaceBuilder(className: ClassName): Builder
        fun funInterfaceBuilder(name: String): Builder
        fun funInterfaceBuilder(className: ClassName): Builder
        fun objectBuilder(name: String): Builder
        fun objectBuilder(className: ClassName): Builder
        fun annotationBuilder(name: String): Builder
        fun annotationBuilder(className: ClassName): Builder
        fun enumBuilder(name: String): Builder
        fun enumBuilder(className: ClassName): Builder
        fun anonymousClassBuilder(): Builder
        fun companionObjectBuilder(name: String? = null): Builder
    }
    fun toBuilder(kind: Kind = this.kind, name: String? = this.name): Builder
}

File and Type Generation

Function and Property Generation

Comprehensive support for generating functions, constructors, properties, and parameters with full Kotlin language feature support including modifiers, annotations, and documentation.

// Function specification
class FunSpec private constructor() {
    companion object {
        fun builder(name: String): Builder
        fun builder(memberName: MemberName): Builder
        fun constructorBuilder(): Builder
        fun getterBuilder(): Builder
        fun setterBuilder(): Builder
    }
}

// Property specification
class PropertySpec private constructor() {
    companion object {
        fun builder(name: String, type: TypeName, vararg modifiers: KModifier): Builder
        fun varBuilder(name: String, type: TypeName, vararg modifiers: KModifier): Builder
    }
}

// Parameter specification
class ParameterSpec private constructor() {
    companion object {
        fun builder(name: String, type: TypeName, vararg modifiers: KModifier): Builder
        fun unnamed(type: TypeName): ParameterSpec
    }
}

Function and Property Generation

Type System

Complete representation of Kotlin's type system including classes, generics, wildcards, lambda types, and type variables. Provides type-safe APIs for working with complex type hierarchies and generic type parameters.

// Base type representation
abstract class TypeName {
    val isNullable: Boolean
    val annotations: List<AnnotationSpec>
    fun copy(nullable: Boolean = this.isNullable, annotations: List<AnnotationSpec> = this.annotations): TypeName
}

// Class and interface types
class ClassName : TypeName {
    companion object {
        fun get(packageName: String, simpleName: String, vararg simpleNames: String): ClassName
        fun get(clazz: Class<*>): ClassName
        fun get(klass: KClass<*>): ClassName
        fun bestGuess(classNameString: String): ClassName
    }
    fun parameterizedBy(vararg typeArguments: TypeName): ParameterizedTypeName
}

// Parameterized (generic) types
class ParameterizedTypeName : TypeName {
    val rawType: ClassName
    val typeArguments: List<TypeName>
    companion object {
        fun get(rawType: ClassName, vararg typeArguments: TypeName): ParameterizedTypeName
    }
}

Type System

Code Generation and Templates

Template-based code generation with placeholder substitution, supporting complex code structures and maintaining proper formatting and imports.

// Code block with template support
class CodeBlock private constructor() {
    companion object {
        fun of(format: String, vararg args: Any?): CodeBlock
        fun builder(): Builder
        fun join(codeBlocks: Iterable<CodeBlock>, separator: String = ", "): CodeBlock
    }
}

// Member reference for imports and qualified names
class MemberName {
    companion object {
        fun get(enclosingClassName: ClassName, simpleName: String): MemberName
        fun get(packageName: String, simpleName: String): MemberName
        fun get(clazz: Class<*>, simpleName: String): MemberName
        fun get(klass: KClass<*>, simpleName: String): MemberName
    }
}

Code Generation and Templates

Annotations and Metadata

Complete support for Kotlin and Java annotations including annotation specifications, JVM-specific annotations, and metadata generation for annotation processors.

// Annotation specification
class AnnotationSpec private constructor() {
    companion object {
        fun builder(type: ClassName): Builder
        fun builder(type: Class<*>): Builder  
        fun builder(type: KClass<*>): Builder
    }
}

// Type alias specification
class TypeAliasSpec private constructor() {
    companion object {
        fun builder(name: String, type: TypeName): Builder
    }
}

Annotations and Metadata

Utilities and Language Support

Essential utilities for name allocation, modifier management, and platform-specific functionality across JVM, JavaScript, and WebAssembly targets.

// Name collision avoidance
class NameAllocator {
    fun newName(suggestion: String, tag: Any? = null): String
    fun get(tag: Any): String
    fun clone(): NameAllocator
}

// Kotlin modifiers
enum class KModifier {
    PUBLIC, PROTECTED, PRIVATE, INTERNAL,
    EXPECT, ACTUAL, FINAL, OPEN, ABSTRACT, SEALED,
    CONST, EXTERNAL, OVERRIDE, LATEINIT, TAILREC,
    VARARG, SUSPEND, INNER, ENUM, ANNOTATION, FUN,
    COMPANION, INLINE, VALUE, INFIX, OPERATOR, DATA,
    CROSSINLINE, NOINLINE, REIFIED
}

// Kotlin operators
enum class KOperator {
    UNARY_PLUS, PLUS, UNARY_MINUS, MINUS, TIMES, DIV, REM,
    PLUS_ASSIGN, MINUS_ASSIGN, TIMES_ASSIGN, DIV_ASSIGN, REM_ASSIGN,
    INC, DEC, EQUALS, NOT_EQUALS, NOT,
    RANGE_TO, CONTAINS, NOT_CONTAINS,
    GT, LT, GE, LE, ITERATOR
}

Utilities and Language Support

Type Definitions

Common Built-in Types

// Core types
val ANY: ClassName
val UNIT: ClassName
val NOTHING: ClassName
val DYNAMIC: Dynamic

// Primitive types
val BOOLEAN: ClassName
val BYTE: ClassName
val SHORT: ClassName
val INT: ClassName
val LONG: ClassName
val CHAR: ClassName
val FLOAT: ClassName
val DOUBLE: ClassName
val STRING: ClassName
val NUMBER: ClassName

// Character and comparison types
val CHAR_SEQUENCE: ClassName
val COMPARABLE: ClassName
val THROWABLE: ClassName
val ANNOTATION: ClassName
val ENUM: ClassName

// Unsigned types
val U_BYTE: ClassName
val U_SHORT: ClassName
val U_INT: ClassName
val U_LONG: ClassName

// Collection types
val ITERABLE: ClassName
val COLLECTION: ClassName
val LIST: ClassName
val SET: ClassName
val MAP: ClassName
val MAP_ENTRY: ClassName
val MUTABLE_ITERABLE: ClassName
val MUTABLE_COLLECTION: ClassName
val MUTABLE_LIST: ClassName
val MUTABLE_SET: ClassName
val MUTABLE_MAP: ClassName
val MUTABLE_MAP_ENTRY: ClassName

// Array types
val ARRAY: ClassName
val BOOLEAN_ARRAY: ClassName
val BYTE_ARRAY: ClassName
val CHAR_ARRAY: ClassName
val SHORT_ARRAY: ClassName
val INT_ARRAY: ClassName
val LONG_ARRAY: ClassName
val FLOAT_ARRAY: ClassName
val DOUBLE_ARRAY: ClassName

// Unsigned array types
val U_BYTE_ARRAY: ClassName
val U_SHORT_ARRAY: ClassName
val U_INT_ARRAY: ClassName
val U_LONG_ARRAY: ClassName

// Wildcard type
val STAR: WildcardTypeName

Core Interfaces

// Tagging support for builders
interface Taggable {
    val tags: Map<KClass<*>, Any>
}

// Documentation support
interface Documentable {
    val kdoc: CodeBlock
}

// Annotation processing support
interface OriginatingElementsHolder {
    val originatingElements: List<Element>
}