Return from setValue


#1

I have a class, wherefore I am building a builder for java-interop.
To make this simple I am using delegated properties.
my code:

class PojoBuilder{
    var firstVar  : Int by Builder(0)
    var secondVar : String by Builder(1)
    //fun build() : Pojo {...}
}

and my builder:

 class Builder<TYPE>(var value: TYPE){
    //operator fun getValue(...){...}
     operator fun <T> setValue(thisRef: T, property: KProperty<*>, value: TYPE) : T {
         this.value = value
        return thisRef
     }
}

I like to be able to do the following:

class Runner{
    public static void main(String[] args){
        PojoBuilder().setFirstVar(10)
            .setSecondVar("stars")
            .build()
    }
}

But the code returns void.
Is it possible to use this just like the set-operator-overloading: If it is set with the operator, then return Unit/void, else return the returnvalue?


#2

No, this is not possible. Have you considered using Kotlin style for your builders?

 PojoBuilder().apply {
    firstVar = 10
    secondVar = "stars"
 }

#3

Yes, but that code doesn’t look that nice from java:

new PojoBuilder().apply(builder->{
    builder.setFirstVar(10);
    builder.setSecondVar("stars")
}).build();