Access to delegate object


#1

Say you have this class:

class SomeClass {

  val obj: String by MyDelegate()

}

Is there any what to get access to the MyDelegate() object that is associated with ‘obj’?


#2

This is not supported yet. The best you can do for now is assign the delegate to a different property:

private val del = MyDelegate() val obj: String by del


#3

This would be pretty nice to have.

Here’s my use case:

I’m creating delegates to represent cascading style properties, which works great, but without an easy way to get at the delegate object itself, it’s not easy to clear its explicit value.

I’d love to be able to do something like this:

class SomeStyle {
var p by StyleProp(0)
}

val host = SomeStyle()
println(host.p) // 0
host.p = 4
println(host.p) // 4
host.::p.clear()
println(host.p) // 0

class StyleProp<P>(
		val defaultValue: P) : ReadWriteProperty<StyleBase, P> {

	private var _explicit: P? = null
	private var _explicitIsSet: Boolean = false

	val explicitIsSet: Boolean
		get() = _explicitIsSet

	internal var _calculated: Any? = null

	@Suppress("unchecked_cast")
	override fun getValue(thisRef: StyleBase, property: KProperty<*>): P {
		return _calculated as P
	}

	override fun setValue(thisRef: StyleBase, property: KProperty<*>, value: P) {
		_explicit = value
		_explicitIsSet = true
		_calculated = value
	}

	val explicit: P
		get() = _explicit!!

	/**
	 * Clears the explicit value.
	 */
	fun clear() {
		_explicit = null
		_explicitIsSet = false
		_calculated = null		
	}
}

#4

Such a feature would be relevant in the discussion in this thread: Unary operator for parameter-less get