Setter overload in Kotlin

When trying to define a setter that accepts a type of parameter that can be used to build a property, as follows:

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

I get an error message:

Setter parameter type must be equal to property type

So what did Kotlin's way of doing this mean?

+5
source share
1 answer

As with Kotlin 1.1, it is not possible to overload property definition tools. The function request is tracked here:

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

Currently, you will need to define the extension function buffer to String :

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

and set the value with

 Foo().buffer = "123".buffer 
+3
source

Source: https://habr.com/ru/post/1266058/


All Articles