Skip to content

Optional field with default #25

@anka-213

Description

@anka-213

Currently, if I want a field to be optional, but have a default instead of Maybe, I would have to do this:

type alias Foo =
  { fieldA : Int
  , newField : Bool
  }

myCodec : Codec Foo
myCodec =
  Codec.object (\fieldA newField -> { fieldA =  fieldA, newField = Maybe.withDefault False newField })
    |> Codec.field "field_a" .fieldA Codec.int
    |> Codec.optionalField "new_field" (Just << .newField) Codec.bool
    |> Codec.buildObject

This is pretty ugly and feels like a hack.
It would be way nicer if it was possible to write something like this (name and argument order is just an example):

myCodec : Codec Foo
myCodec =
  Codec.object Foo
    |> Codec.field "field_a" .fieldA Codec.int
    |> Codec.optionalFieldWithDefault "new_field" .newField Codec.bool False
    |> Codec.buildObject

I think it should be easy to implement, but ObjectCodec being opaque means it can't be implemented externally.
I can submit a PR if this is 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