dimanche 18 juin 2023

How to iterate over class properties in Kotlin

I have an abstract class ConfigGroup that has the super class ConfigElement. In ConfigElement a method toJson() is definded. ConfigGroup overrides this method.

Currently toJson() in ConfigGroup looks like this:

override fun toJson(): JsonObject {
        val map: HashMap<String, JsonObject> = HashMap()
        for (child in this::class.declaredMemberProperties) {
            map[child.name] = (child.get(this) as ConfigElement).toJson()
        }
        return JsonObject(map)
    }

But when I try to compile it I get Type mismatch: inferred type is ConfigGroup but Nothing was expected

I am a bit confused since it is almost the same as the example in Kotlin: Iterate over components of object . The only difference being that I try to get the properties from within the same class and therefore have to use the this keyword.





Aucun commentaire:

Enregistrer un commentaire