Kotlin-创建返回类实例的setter

时间:2018-07-19 06:30:58

标签: kotlin

是否可以自动创建返回this的设置器?

尝试了以下方法,但这种方法不起作用,但是此示例显示了我想要实现的目标:

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

手动解决方案

写出自己settersgetters的方式,例如:

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

问题

可以使用Kotlin自动执行此过程吗?任何想法如何实现这一目标?

1 个答案:

答案 0 :(得分:0)

您似乎在看builder pattern,为此您可能会在Kotlin中使用DSL over链式设置器。

最简单的内置方法是使用带有receiver的“块”(引号,因为with是Kotlin的适当功能,在这里没有什么魔术):

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

或者类似地:

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

有关构建不可变实例的更详细的示例,请参见here。官方文档中也有more on this topic

相关问题