Kotlin: A default-ish setter that returns "this"

Viewed 2906

I know it's not "strictly by the design pattern" blah blah blah, but...

In Kotlin, is there a way to create a "default-ish" setter that returns "this", like

var foo:Bar = Something()
    set(f:Bar) {
       foo = f
       return this // Alas, that would not compile because Setter returns Unit
    }

It is very convenient when a setter return this, because can then make a Builder pattern without having to declare a Builder. It's just shorter to do:

BlahBlah().setFoo(x).setFoo2(y)...

Than

BlahBlah.Builder().setFoo(x)....

or

var b = BlahBlah()
b.setFoo(x)
b.setFoo2(y)
...

Or whatever

And besides, if a setter returns Unit anyway, why not this just as well?

3 Answers
Related