Search code examples
kotlincovariance

kotlin: list properties of any object - variance error


I'm trying to write a function that produces map of properties and values for any type

inline fun <reified T : Any> T.propertiesMap() {
    for (property in this::class.memberProperties) {
        property.get(this)
    }
}

i get a compilation error in property.get(this) about

out-projected type [...] prohibits the use of 'public abstract fun get(receiver...


Solution

  • The issue is that this::class produces a KClass<out T> instead of KClass<T> which is what would be needed to use anything of type T in the property.get(...) call. So you can do an unchecked cast to do what you want:

    fun <T : Any> T.propertiesMap() {
        @Suppress("UNCHECKED_CAST")
        for (property in (this::class as KClass<T>).memberProperties) {
            property.get(this)
        }
    }
    

    Which does not require the function to be inline nor reified type parameter. Otherwise you can change your function to use T::class instead of this::class to create a matching KClass<T>.

    inline fun <reified T : Any> T.propertiesMap() {
        for (property in T::class.memberProperties) {
            property.get(this)
        }
    }