Setter overloading in Kotlin

2019-06-20 00:54发布

问题:

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


标签: kotlin setter