Check to see if object has a function/variable

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)

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 Likes

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

After checking the member method, is there a smart cast in that block to be able to call the method?

Unfortunately, the classes which have the same kind of methods are outside of my control so I can’t make them implement some interface.

I’d suggest that you look at the wonderful land of Arrow and Arrow Meta. Beware tho, most of this stuff will be incredibly confusing, but once you get it you’ll be able to effectively make objects outside of your control implement an interface