Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
lmeadors opened this issue Mar 9, 2022 · 0 comments
Open

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

lmeadors opened this issue Mar 9, 2022 · 0 comments

Comments

@lmeadors
Copy link
Contributor

lmeadors commented Mar 9, 2022

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant