Basel Shishani
Basel Shishani

Reputation: 8177

Setter overloading in Kotlin

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?

Upvotes: 10

Views: 2881

Answers (1)

Ingo Kegel
Ingo Kegel

Reputation: 47965

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

Upvotes: 7

Related Questions