Setter overloading in Kotlin

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-10 13:23:33

问题


When trying to define a setter that accepts a parameter type that can be used to construct a property, thusly:

class Buffer(buf: String) {}

class Foo {
    var buffer: Buffer? = null
        set(value: String) {
            field = Buffer(value)
        }
}

I get the error message:

Setter parameter type must be equal to the type of the property

So what's meant to be the Kotlin way of doing this?


回答1:


As of Kotlin 1.1 it is not possible to overload property setters. The feature request is tracked here:

https://youtrack.jetbrains.com/issue/KT-4075

Currently, you would have to define a buffer extension function on String:

val String.buffer : Buffer
    get() = Buffer(this) 

and set the value with

Foo().buffer = "123".buffer


来源:https://stackoverflow.com/questions/43086327/setter-overloading-in-kotlin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!