Question: Suppose I have this: ```open class MyFla...
# getting-started
k
Question: Suppose I have this:
Copy code
open class MyFlagDelegate(property: KProperty0<Int>) : ReadOnlyProperty<Any?, Boolean>
class MyMutableFlagDelegate(property: KMutableProperty0<Int>) : MyFlagDelegate(property), ReadWriteProperty<Any?, Boolean>
Is it possible to create an extension function on
Int
that returns one of these two delegates, and properly supplying the
property
argument? ie.
Copy code
var myInt: Int
var myFlag: Boolean by MyMutableFlagDelegate(::myInt)
var myFlagAgain: Boolean by myInt.doSomething() // <-- something like this
n
Well, in this case
myInt
is still just of type
Int
, so what you can do is create a
doSomething
extension function on
Int
that returns a
ReadWriteProperty
instance like the following:
Copy code
fun Int.doSomething() = object : ReadWriteProperty<Any?, Boolean> {
    override fun getValue(thisRef: Any?, property: KProperty<*>): Boolean = TODO()
    override fun setValue(thisRef: Any?, property: KProperty<*>, value: Boolean) = TODO()
}
Alternatively you could also add an operator
provideDelegate
extension function directly on
Int
that returns a property delegate, so you do not need to call a special extension function on
Int
. https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.properties/-property-delegate-provider/provide-delegate.html Example:
Copy code
operator fun Int.provideDelegate(thisRef: Any?, property: KProperty<*>) =
    object : ReadWriteProperty<Any?, Boolean> {
        override fun getValue(thisRef: Any?, property: KProperty<*>): Boolean = TODO()
        override fun setValue(thisRef: Any?, property: KProperty<*>, value: Boolean) = TODO()
    }