vendredi 8 juin 2018

Kotlin how to make sure that generic parameter is subclass of receiver class

I tried to implement quick field accessor function, and also wanted to make sure, that specified class (real owner of the field) is superclass of the receiver type, thus I wrote it as following:

inline fun <A : B, reified B: Any> A.getProperty (name: String): Any {
    return B::class.java.getDeclaredField(name).apply { isAccessible = true }.get(this)
}

But this makes me pointlessly write receiver type during invocation:

// in SubClass
getProperty<Subclass, BaseClass>("fieldThatIsInBaseClass")

In case when field is defined in current class, it doesn't even need parameters to my surprise:

// in BaseClass
getProperty("fieldThatIsInBaseClass")

I also tried to add field type parameter to the function, but that breaks code above, and in every case all parameters have to be specified:

inline fun <T, A : B, reified B: Any> A.getProperty (name: String): T {
    @Suppress("UNCHECKED_CAST")
    return B::class.java.getDeclaredField(name).apply { isAccessible = true }.get(this) as T
}

And example how this breaks things:

// in a class Example which declares the field
getProperty<Example, Example, Int>("someIntField")

The ideal syntax in a class that defines field should be:

getProperty<Int>("someIntField")

And for class that extends some base class:

getProperty<BaseClass, Int>("fieldThatIsInBaseClass")

Is something like that possible?





Aucun commentaire:

Enregistrer un commentaire