3

Is it possible to create setters automatically that return this?

Tried following, but this way it's not working, but this example shows what I want to achieve:

var pos: Int?
    set(value) : IPosItem {
        this.pos = value
        return this
    }

manual solution

Write setters and getters myself of coure, like following:

var _pos: Int?
fun getPos(): Int? = _pos
fun setPos(value: Int?): IPosItem {
    _pos = value
    return this
}

Question

Can this process be automated with kotlin? Any ideas how to achieve this?

prom85
  • 16,896
  • 17
  • 122
  • 242
  • 3
    Unless the goal is to create a Java API in Kotlin, you shouldn't need that, because simply using apply() allows avoiding repeating the variable name as you would have to do in Java, and would be idiomatic Kotlin. https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/apply.html – JB Nizet Jul 19 '18 at 06:48
  • 1
    And if the goal is to create a Java API, then a method returning something other than void is not a setter. It's a method. – JB Nizet Jul 19 '18 at 06:50
  • I need this because an annotation processor I use generates such types of setters, so I want to use above in my custom interface of which I tell the processor that the generated class is implementing... – prom85 Jul 19 '18 at 06:50

1 Answers1

0

You seem to be looking at a builder pattern, for which you'd probably use a DSL over chained setters in Kotlin.

The easiest, built-in way is to use a "block" with receiver (quotation marks because with is a proper Kotlin function, no magic here):

val newThing = Thing()
with ( newThing ) {
    pos = 77
    otherValue = 93
}

Or, similarly:

val newThing = Thing().apply {
    pos = 77
    otherValue = 93
}

See here for a more elaborate example that builds immutable instances. The official documentation also has more on this topic.

Raphael
  • 9,779
  • 5
  • 63
  • 94