in pure Java I often used freebuilder [0] to automatically generate builders from interfaces.
Now, as I convert many of these interfaces into kotlin-classes and using them from Java, I wish I could somehow have a builder from kotlin-constructors, so I can do:
new Class()
.setPropA()
.setPropB()
.setPropC()
I thought about using setters with default parameters, but they don’t allow me to return this.
Is there some language trick which makes this easier for me?
You (kind of) have to create a separate mutable builder. In Kotlin, you could have a public constructor that takes a configuration closure that has this builder (or an interface for a builder) as parameter. The builder would then be passed so another constructor that uses it to initialise the actual class. It is possible in plain Java to implement such a closure and use it in the same way. Otherwise, go for the more explicit builder pattern.
interface IBuilder {
var x:Int
fun withX(val:Int):IBuilder
var y:Int
fun withY(val:Int):IBuilder
fun build():MyClass
/*....*/
}
private class MyBuilder:IBuilder { /*......*/ }
class MyClass private constructor(myBuilder: MyBuilder) {
companion object { // This below is only to be nicer to pre-8 Java, post-8 Java should hapily use a lambda
@JvmStatic
fun builder:IBuilder() = MyBuilder()
}
val x = myBuilder.x
val y = myBuilder.y
constructor(config:IBuilder.()->Unit):this(MyBuilder.apply(config))
}
fun makeMyClass() {
MyClass { x=5; y=10 }
}