https://kotlinlang.org logo
#getting-started
Title
# getting-started
j

James Whitehead

08/24/2021, 11:36 AM
Hi all, sorry if this isn't the place for this, I tried in #reflect but didn't get any responses 😞 A couple of questions with respect to reflection: 1. Is there an equivalent in Kotlin Reflect to Java's 
isInterface
 ? I see we have 
isAbstract
 , 
isOpen
 , etc, but I haven't found anything for interface. 2. Follow up question; is 
MyClass::class.java.interfaces
 the recommended way to get the interfaces implemented by a given class?
i

Ivan Pavlov

08/24/2021, 12:05 PM
1. Looks like the only way is to use java API (I didn't found any kotlin-reflect way to do that). The first link in google shows the same answer https://stackoverflow.com/questions/48568268/how-to-distinguish-between-a-class-and-an-interface-in-kotlin-using-kclass-refle
👍 1
2. In kotlin you can get
supertypes
or
allSupertypes
and process them somehow I guess
r

Rob Elliot

08/24/2021, 1:58 PM
Is it fair to say that a class without constructors must be an interface? If so:
val KClass<*>.isInterface get() = constructors.isEmpty()
should work.
i

Ivan Pavlov

08/24/2021, 2:01 PM
@Rob Elliot from the answer on stackoverflow
Please note that the constructors counting solution might not be very precise for general purpose use. For example, Kotlin package facade classes do not have any constructors either, but they are not interfaces (UPD: and their constructors cannot even be reflected with 
kotlin-reflect
, just as those of anonymous classes, 
KFunction
 and maybe more).
👍 1
r

Rob Elliot

08/24/2021, 2:03 PM
Cool, thanks, should have followed the link first edit - drat, if I’d only clicked before writing this I could have blamed it on stackoverflow being down for maintenance…
👍 1
j

James Whitehead

08/24/2021, 11:06 PM
Thanks @Ivan Pavlov, only problem with the supertypes approach is that you also get
Any
So through some experimentation with the debugger and some simple unit tests I discovered that
KClass.isAbstract
returns
true
for an interface. Which is fine for my use case, but probably not very helpful if one were trying to distinguish between a class, abstract class and an interface.