Kotlin: set-ish setter that returns "this"

I know this is not "strictly a design pattern" blah blah blah, but ...

There is a way in Kotlin to create a "default-ish" installer that returns " this

", for example

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

      

It is very handy for the setter to return this

because it can then make a Builder template without declaring a Builder. It will be much shorter:

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

      

Than

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

      

or

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

      

Or something else

And besides, if the setter returns Unit

anyway, why not this

?

+3


source to share


3 answers


Kotlin has nice documentation on how to create type-safe fonts . Installers in Kotlin are called like

receiver.property = value

      



Returning this

from the setter method will only help if the code is used from Java. Having said that the setter Kotlin must return Unit

. Even without a specialized builder, the typical task of setting multiple object properties in Kotlin is much more concise:

class BlahBlah {
  var name = "John"
  var age = 12
}

BlahBlah().apply {
  name = "Sarah"
  age = 10
}

      

+8


source


No, this is not possible: Kotlin setters return Unit by design.

The Builder pattern exists to overcome the problem where increasing the combinations of constructor parameters results in an exponential list of constructors. In Kotlin, this problem is solved with the default parameter values:

data class Foo(
  val a1: String = "a1",
  val a2: String = "a2"
)

      

Instead of using the Builder template, you can now easily skip parameters by calling them:



val foo = Foo(a1 = "bar")

      

If you really want to have some kind of Builder:

class FooBuilder {
    var a1: String = "a1"
    var a2: String = "a2"

    fun build() = Foo(a1, a2)
}

val foo = FooBuilder().apply {
  a1 = "bar"
}.build()

      

However, this requires a lot more code.

+2


source


Please have a look at How to Implement the Builder Pattern in Kotlin?

There is no built-in mechanism, but you can use apply

to easily write self-return methods:

class Foo {
    var bar: Bar
    fun bar(b: Bar) = apply { bar = b }
}

      

+2


source







All Articles