Hi, I have an issue, which seems to be related to...
# announcements
j
Hi, I have an issue, which seems to be related to this post on the kotlin forums: https://discuss.kotlinlang.org/t/kmutableproperty0-from-an-interface-variable/13884 In summary, if you have a class with a field of another interface, when you try and access its delegate with reflection it returns null. This is because it gets the KProperty of the interface and not the current concrete instantiation. Is there a way to make it pick up the KProperty of the instance?
interface I {
}
class C: I {
var x: String by someDelegate()
}
class T {
var i: I = C()
}
T().i::x.getDelegate()
-> returns null
C()::x.getDelegate()
-> returns the someDelegate instance
n
I'm very far from expert in these matters but it seems like you'll need to perform a cast here
somewhere
T().i
can be cast to a C
I don't think you could do
T().i::x.getDelegate()
and then ask it to give you back something if the instance there happens to have an
x
, you'd need to do the cast to a known derived interface/class that has an
x
and then ask for it
you could have two classes inheriting from I with totally unrelated x's for example
j
Sure, but I was hoping for me a generic solution, i.e. it auto casts to x based on what the current value is, seems like this may not be possible though
n
it's kind of hard to imagine this working in a statically typed language
granted, reflection in kotlin/java is fairly dynamic
but, I guess, not that dynamic
but yeah, i know it's the cliche and annoying thing to say, but that would probably be a good point to re-examine why you want to do it. Some people will go a step further and auto-criticize almost any usage of reflection; I find such criticisms annoying and baseless, reflection is very useful, but wanting to do this seems more dynamic than should really be necessary
https://www.baeldung.com/java-reflection-class-fields this article mentions inherited fields as well
ah seems like its talking about the opposite direction though
j
Yeh, you are right there. I think the problem is, is that any other solution is much more verbose. Which ultimately is fine, just wondered if there was something I was missing. Appreciate the help though 🙂
n
i don't think I helped much but glad it was some value 🙂 I guess the obvious solution is to have a sub-interface that specifies
x
, and you can do this for as many fields as you want
and have your classes inherit from multiple interfaces as necessary
Or honestly maybe just convert your classes into
Map<String, Any>
at some point, and then operate on that instead? That's basically what you're asking for
y
Maybe try doing
(T().i as C)::x.getDelegate()