Skip to content

Kotlin Extensions

Damian Malczewski edited this page Sep 13, 2026 · 2 revisions

Kotlin Extensions

KotlinExtensionMaker emits a mutate { } extension function per generated type - a Kotlin-idiomatic, DSL-shaped wrapper around the Java builder.

Enabling

Two conditions, both required:

plugins {
    kotlin("jvm") version "..."                              // 1. the Kotlin JVM plugin
    id("io.github.malczuuu.modelmaker") version "..."
}

modelmaker {
    kotlin { enabled = true }                                // 2. the flag
}

Miss either one and generateModelKotlin produces nothing - and deletes its output directory, so a previously generated .kt file does not linger.

What is generated

One file per schema, named <Name>Extensions.kt, in the type's package:

src/main/model/kotlin/com/example/dto/WidgetExtensions.kt
package com.example.dto

// Generated by ModelMaker (io.github.malczuuu.modelmaker). Do not edit manually.

public inline fun Widget.mutate(block: Widget.BuilderMutator.() -> Unit): Widget =
    this.mutate().also { it.block() }.build()

A type with no properties gets no extension - and, if it is the only type in the file, the file holds just its package line.

Usage

val widget = Widget.builder()
    .id("w-1")
    .name("Widget")
    .build()

val renamed = widget.mutate {
    name("Renamed")
    note("changed in flight")
}

Compare with the Java form:

Widget renamed = widget.mutate().name("Renamed").note("changed in flight").build();

Same object, same builder - the Kotlin version only removes the chaining and the trailing build().

Why the receiver is BuilderMutator

The block receives BuilderMutator, the sealed interface that exposes the builder's setters but not build(). The block can only configure; building stays with the extension function, so a half-built builder cannot escape the lambda.

Nested types

Nested types get their own extension in the same file, addressed through the outer class:

public inline fun Kit.Contact.mutate(block: Kit.Contact.BuilderMutator.() -> Unit): Kit.Contact =
    this.mutate().also { it.block() }.build()

Where the file lands

src.enabled Kotlin output
false (default) build/generated/sources/modelmaker/kotlin/main
true src/main/model/kotlin

The directory is registered on the main source set, so the Kotlin plugin compiles it with no extra configuration.

Notes

  • The DTOs themselves are always Java - kotlin { enabled = true } adds extensions, it does not switch the generator to Kotlin output.
  • The extension is inline, so there is no wrapper object at runtime.
  • Generated classes are @NullMarked, which Kotlin honors: a required property is a non-null Kotlin type, an optional one is nullable.
  • Like the Java output, the Kotlin directory is wiped and rebuilt on every run.

Clone this wiki locally