Search code examples
androidclasskotlinenumsgson

How to use getDeclaringClass in Kotlin?


I have this method:

    protected <E extends Enum<E>> E getEnum(JSONObject jsonObject, String propertyName, E fallbackEnum)
{
    String fallbackString = GsonXelion.toJson(fallbackEnum);
    String jsonString = getString(jsonObject, propertyName, fallbackString);
    E enumUsingGson = getEnumUsingGson(jsonString, fallbackEnum.getDeclaringClass());
    return enumUsingGson != null ? enumUsingGson : fallbackEnum;
}

I tried to convert into kotlin and got this:

  protected fun <E : Enum<E>?> getEnum(jsonObject: JSONObject, propertyName: String?, fallbackEnum: E): E {
    val fallbackString = toJson(fallbackEnum)
    val jsonString = getString(jsonObject, propertyName, fallbackString)
    val enumUsingGson: E = getEnumUsingGson(jsonString, fallbackEnum.getDeclaringClass())
    return enumUsingGson ?: fallbackEnum
}

And getDeclaringClass() is not recognized in kotlin. I tried using fallbackEnum::class.java but then I get this error:

enter image description here

What am I doing wrong?


Solution

  • The code from Java is following:

    getEnumUsingJson(String, Class<declaring class of E>
    

    but, in Kotlin, what you do is:

    getEnumUsingJson(String, Class<E>)
    

    So your implementation for Kotlin is different from the original one in Java (deducted type is not compatible with any of possible signatures).

    So, what you can do about it? Just pass declaring class of E (instead of just E):

    getEnumUsingJson(jsonString, fallbackEnum::class.java.declaringClass)