jdemeulenaere
10/25/2019, 12:56 PMReadWriteProperty#setValue
so that we could set a variable from different types. Something like this:
import kotlin.reflect.KProperty
interface Named {
val name: String
}
class MyClass {
var name by NameDelegate("foo")
}
class NameDelegate(private var name: String) {
operator fun getValue(thisRef: MyClass, property: KProperty<*>): String {
return name
}
operator fun setValue(thisRef: MyClass, property: KProperty<*>, value: String) {
name = value
}
operator fun setValue(thisRef: MyClass, property: KProperty<*>, value: Named) {
name = value.name
}
}
fun main() {
val namedImpl = object : Named {
override val name: String = "bar"
}
val myObject = MyClass()
myObject.name = "bar" // this compiles
myObject.name = namedImpl // this does not compile
}
Hullaballoonatic
10/25/2019, 5:58 PMor
operator in type parameters (which has been proposed numerous times), but your idea is simpler:
operator fun setValue(thisRef: MyClass, property: KProperty<*>, value: String | Named) {
name = value.toString()
}
karelpeeters
10/25/2019, 8:25 PMname
? The way it works right now is that a property has a single type and both the setter and getter share that type.ilya.gorbunov
10/25/2019, 10:50 PMjdemeulenaere
10/27/2019, 2:48 PMjdemeulenaere
10/27/2019, 2:52 PMjdemeulenaere
10/27/2019, 2:53 PMNameDelegate
implement ReadWriteProperty<MyClass, String>