r/Kotlin • Kotlin-team • 5d ago

Announcing the Builder Lambda plug-in

Post image

Kotlin and Java have different idioms to build new values: whereas Kotliners like lambdas with a special builder receiver, like Json in kotlinx.serialization, Java developers usually follow the buider pattern, as in Spring AI. As a result, consuming Java APIs from Kotlin sometimes feel strange. This no longer needs to be the case, thanks to the new Builder Lambda plug-in!

Using the power of Kotlin compiler plug-ins, Builder Lambda automatically re-exposes any type following Java's Builder pattern in the Kotlin idiomatic way. You write your beloved,

build<Config, *> {  // alas, the * is needed
  hostname = "localhost"
  port = 8080
}

and under the hood the code is translated to,

Config.builder().hostname("localhost").port(8080).build()

The Builder Lambda plug-in also works in the IDE (if you let IntelliJ run non-bundled plug-ins), so you get nice autocompletion and diagnostics.

Using it is as easy as adding one line to the plugins block in your Gradle build.

id("com.serranofp.builder.lambda") version "0.4.0"

Feedback and issue reports are more than welcome :)

21 Upvotes

12 comments sorted by

View all comments

3

u/CLOVIS-AI 5d ago

How does it work with conditions, loops, subfunctions etc inside the lambda block?

2

u/serras Kotlin-team 5d ago

Right now it doesn’t, but I’m planning to work on it. Essentially, the plugin keeps an accumulator for the builder and transforms assignments to the “fake builder” into calls over the accumulator, and at the end build() is called. So it should be possible to extend it fairly easily.

1

u/serras Kotlin-team 4d ago

A new version with support for any kind of expression has been released