Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Using a TypeAdapter with a default class for null? #353

@lmeadors

Description

@lmeadors

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions