Encoders and Decoders for Enums/Custom Types #700
frnco
started this conversation in
Language Development
Replies: 1 comment
-
I'm converting this into a discussion since this feels more of a discussion topic. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
One issue I've encountered a few times now is dealing with record fields that have a set number of possible values. When the value for a field is a basic type, or is either a basic type or something like
Null
(OrMaybe::Nothing
if we're considering Mint), it's fairly straightforward, I just use the type or aMaybe()
with the basic type as argument. But sometimes I need a record field's value to match any one item from a set/list/array/call-it-what-you-may. In those cases I tend to use Enums, which doesn't actually make use of the whole Algebraic Data Type thing, but can actually be pretty helpful with validation-related stuff. To list a few examples of how and why I use that are:store Settings
to track the user's preferences, persist it and automatically remember it on future sessions, and I decided to allow the use of different fonts/font-sizes/etc on the Ui and the Content, thus anenum FontScope
with the optionsUi
andContent
seemed perfect for the job, and would allow me to use the samerecord
in both.Using Enums for that stuff is all fine and dandy until you try to (de)serialize this data. If the data structure is simple enough it is not too painful to manually convert and check stuff, but as the data structures get more complex, converting it to and from
Object
(Or evenJson
) becomes REALLY painful. I was looking into that when I found #146 and it blew my mind, and I think at the very least that should be in the documentation, maybe in a simplified way, along with a similar example for encoding.And even more than that, maybe there could be an easier way to write custom encoders/decoders. One common problem I've faced is converting
Enum
values to strings and vice-versa, and usually that ends with two functions, each with a case expression that takes either a string or said Enum and outputs the other, which obviously means I have to write the conversion thing twice, one for each direction, and that's far from ideal.Having at least some examples of how to deal with those kinds of situations included in the Documentation would be really helpful.
Beta Was this translation helpful? Give feedback.
All reactions