CodeBuilder

class CodeBuilder(classesToImport: MutableMap<String, String> = mutableMapOf(), functionsToImport: MutableMap<String, MutableSet<String>> = mutableMapOf(), indentDepth: Int = 0, varCounts: MutableMap<String, Int> = mutableMapOf())

A class to simplify Kotlin code generation.

This is a simple, but somewhat more Kotlinized alternative to Kotlin Poet (which is basically a Java Poet port). Kotlin code generation is still emerging it seems, and better libraries may exist in the future. Consider them before adding too much functionality to this class.

Constructors

Link copied to clipboard
constructor(classesToImport: MutableMap<String, String> = mutableMapOf(), functionsToImport: MutableMap<String, MutableSet<String>> = mutableMapOf(), indentDepth: Int = 0, varCounts: MutableMap<String, Int> = mutableMapOf())

Functions

Link copied to clipboard
fun append(value: Int)

Appends given integer.

fun append(code: String)

Appends given code.

Link copied to clipboard
fun block(before: String, hasBlockAfter: Boolean = false, hasBlockBefore: Boolean = false, lambdaParameters: String = "", lambda: CodeBuilder.() -> Unit)

Adds a construct that is followed by Kotlin block/lambda (code in curly braces).

Link copied to clipboard
fun emptyLine()

Add an empty line to the code.

Link copied to clipboard
fun endLine()

Ends line (appends newline character).

Link copied to clipboard
fun importFunctionName(function: String, packageName: String)

Add and import for a function from a given package.

Link copied to clipboard
fun importQualifiedName(clazz: KSClassDeclaration)

Add given class to import list, simple class name can then be used in the code to refer to it.

fun importQualifiedName(qualifiedName: String)

Import class or function using its fully-qualified name.

Link copied to clipboard

Creates an insertion point where some code can be added later (until writeToFile is called).

Link copied to clipboard
fun line(lambda: CodeBuilder.() -> Unit)

Generate a line of code in a lambda

fun line(code: String)

Add a line with the given code.

Link copied to clipboard
fun optionalBlock(before: String?, lambda: CodeBuilder.() -> Unit)

If before is not null, behaves like block, simply executes lambda otherwise.

Link copied to clipboard
fun startLine()

Starts new line indenting it according to the current indent depth.

Link copied to clipboard
fun varName(base: String = "tmp"): String

Reserve a new unique variable name using base name.

Link copied to clipboard
fun withIndent(lambda: CodeBuilder.() -> Unit)

Executes given lambda with increased indent depth.

Link copied to clipboard
fun writeToFile(codeGenerator: CodeGenerator, dependencies: Dependencies, packageName: String, fileName: String)

Write generated kode to a new source file in context of KSP.