Skip to content

Alternative Enum adapter with default value #1812

Open
@nikclayton

Description

There's already support for parsing enum values with unrecognised values, EnumJsonAdapter with a fallback.

Moshi moshi = new Moshi.Builder()
    .add(CurrencyCode.class, EnumJsonAdapter.create(CurrencyCode.class)
        .withUnknownFallback(CurrencyCode.USD))
    .build();

However, I'm a bit concerned that the choice of default is happening as the adapter is added to Moshi. This can be quite far in the code from where the enum is defined, so whoever is reading the code has to look in multiple places to understand how the enum will be processed.

Below is an alternative I'm offering up for discussion / feedback (I'm sure the code can be improved).

You add the adapter as normal:

val moshi = Moshi.Builder().add(HasDefault.Factory()).build()

and then add two annotations to enums that have defaults; the first marks it as an enum that has a default, and the second marks the actual enum to use as the default:

@HasDefault
enum class CurrencyCode { EUR, CHF, GBP,  @Default USD }

I have a variant that would let you write:

@DefaultEnum(value = "USD")
enum class CurrencyCode { EUR, CHF, GBP, USD }

but I'm not sure of the wisdom of that approach when tools like ProGuard might (without careful configuration) rewrite enum names (this would be much easier to write if annotations could be generic...)

The code's at https://gist.github.com/nikclayton/999558150bfdd48e93f12b8754694eed. If this is interesting to people I'm happy to prep a PR for inclusion.

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions