klaxon icon indicating copy to clipboard operation
klaxon copied to clipboard

Using a TypeAdapter with a default class for null?

Open lmeadors opened this issue 3 years ago • 0 comments

Looking in the code, it's not possible to specify a default class for a type adapter where the discriminator is null because we do this:

val discriminant = jsonObject[discriminantFieldName] as Any
polymorphicInfo.adapter.createInstance().classFor(discriminant)

If the field is not present, this blows up - we could support this in a back-compatible way by doing this instead:

val discriminant = jsonObject[discriminantFieldName]
polymorphicInfo.adapter.createInstance().classForNullable(discriminant)

In the TypeAdapter interface, we can add a default method like this:

interface TypeAdapter<Output> where Output: Any {
    fun classFor(type: Any): KClass<out Output>
    fun classForNullable(type: Any?): KClass<out Output>{
        return classFor(type as Any)
    }
}

For people who want the current behavior, no change is required - the as Any in the default method will throw the same exception, and existing implementations of the interface are still valid because the new methods has a default.

For people who want to allow null, they can do so by implementing the new classForNullable(type: Any?) method.

I would be happy to provide a PR for this, if desired.

lmeadors avatar Mar 09 '22 13:03 lmeadors