Inline classes could use inline property delegate

Inline classes cannot use delegates for properties.
However, in some cases, it might be technically possible to do so if the delegate is also an inline class.

Here I show a possible use case where this could be useful and how the current solution is verbose and limiting.

import kotlin.reflect.KProperty

fun staticGetValue(id: Int): String {
    // Do stuff
    return ""
}

fun staticSetValue(id: Int, value: String) {
    // Do stuff
}

inline class InlineDelegate(val id: Int){

    operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
        return staticGetValue(id)
    }

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
        return staticSetValue(id, value)
    }

}

inline class InlineWrapper(val something: String){

    // I can do this, verbose and non-ideal
    var property: String
        get() = staticGetValue(3)
        set(value) = staticSetValue(3, value)

    // What I would like to do instead:
    var propertyDelegate by InlineDelegate(3)
}

fun main(){
    InlineWrapper("Hello").apply {
        property = "World"
        propertyDelegate = "!"
    }
}

IIRC, you can define it as an extension property which then should get you your intended result:

var InlineWrapper.propertyDelegate by InlineDelegate(3)
1 Like

The id needs to be stored somewhere even if InlineDelegate is not.

The restriction would need to ensure that there’s no state at all needed per instance (essentially there is no instance).

Seems like allowing object types to be delegates would work.

open class InlineDelegate(val id: Int){

    operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
        return staticGetValue(id)
    }

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
        return staticSetValue(id, value)
    }

}

object InlineDelegateObject : InlineDelegate(3)

inline class InlineWrapper(val something: String){
    var propertyDelegate by InlineDelegateObject
}

Doubt there’s a ton use cases where that’d be helpful though.

1 Like