Java Builder for Kotlin Class

Hi,

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?

Fabian Zeindl

[0] GitHub - inferred/FreeBuilder: Automatic generation of the Builder pattern for Java

How about this: https://kotlinlang.org/docs/reference/idioms.html#calling-multiple-methods-on-an-object-instance-with

How do I use this from inside Java?

Hmm, I don’t think it is possible.

:(.

Is there a good way for using building immutable Kotlin Objects with a lot of members from Java?

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 }
}

In Java 6/7

static void makeMyClass() {
  MyClass foo = MyClass.builder.withX(5).withY(10).build()
}