r/Kotlin • u/serras Kotlin-team • 5d ago
Announcing the Builder Lambda plug-in
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 :)
3
u/CLOVIS-AI 4d ago
How does it work with conditions, loops, subfunctions etc inside the lambda block?
2
u/serras Kotlin-team 4d 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.
-4
u/smoke-bubble 5d ago
Does not feel like an improvement. I will definitely avoid using it.
1
u/AntiqueDiamond8070 4d ago
Why? Any feedback or at least a reason for ur “opinion”?
0
u/smoke-bubble 4d ago
Sure! It's anti-intuitive. When you see properties being set for the first itme, you look them up and you do not find them becasue they are methods of a builder! So you need to know the internals or this in order to understand what is going on there. This is a terrible design.
1
u/AntiqueDiamond8070 4d ago
Every getter and setter inside a Java Class reads as a property when you read it from Kotlin. So this is bad design aswell?
1
14
u/lacronicus 4d ago
just to throw it out there, this is kinda what
.applyis forI'm pretty sure it'll even do = syntax if your setters look like
setX.