Check to see if object has a function/variable


#1

I just started messing around with Kotlin and one of the features that I miss from Groovy is the “responds to” method. Each object in Groovy can be checked to see if it has a method, as opposed to seeing if it is an instance of a class. While instance checking is nice, sometimes it could be useful to not need to know the specifics of the object (like if you had an array of different objects that all had a name variable and you wanted to get the name of objects, irrelevant of their individual superclasses.) I feel like a very nice option would be a way to check if an object has a variable or a function.

To my knowledge there’s really no “hacky way” to check this either, (if there is please direct me to it. :P)


#2

You can use reflection for this purpose.

myObject.javaClass.kotlin.members.any { it.name == "yourName" }

Note that in Kotlin a better design to express the idea of “objects that all have a name variable” would be to define an interface and have all those objects implement it:

interface Named { val name: String }


#3

Oh, neat! didn’t know about that. Thanks!