jeudi 17 février 2022

Generic Parameter Requires type "Nothing" when T is type "Any"

I am a new Kotlin programmer, and I am having a problem relating to generics

In the following code, I am getting an error with it.get(this) "Type mismatch. Required: Nothing. Found: Any.

inline fun <reified T : Any> Any.getPropertiesWithType() =
    this::class.memberProperties
        .filter { it.returnType.isSubtypeOf(T::class.starProjectedType) }
        .map {
            it.isAccessible = true
            it.get(this) as T
        }

This is confusing because memberProperties returns a Collection<KProperty1<T, *>> where T is the type of this, which is Any in my case. KProperty1.get() takes one argument of that same type T, so I would expect Any could be passed without an issue.

One thing I noticed is that it in the filter and map are both type KProperty<out Any, *>> but memberProperties does not have the out variance.

If I replace this::class with this.javaClass.kotlin, it works without an error, but that seems like a very bad way to go about this.

If anyone knows a way to fix this, or an entirely different strategy, it would be much appreciated. I am new to Kotlin and still do things in the Java way sometimes.





Aucun commentaire:

Enregistrer un commentaire