How to remove duplication from typespec and static list of values?

Background

I have a structure where the new function requires a parameter to be part of a closed set of values (think of it as an enum).

So what I am doing is that I am basically duplicating them in the following way:

defmodule Car do
  
  @type brands ::
          :opel
          | :mercedez
          | :citroen
          | :audi

  @brands [
    :opel,
    :mercedez,
    :citroen,
    :citroen,
    :audi
  ]

  @type t :: %__MODULE__{
          type: String.t(),
          brand: brand(),
          seats: pos_integer()
        }

  defstruct [
    :type,
    :brand,
    :seats
  ]

  def new(type, brand, seats) when is_binary(type) and brand in @brands and seats > 0 do
     %__MODULE__{
       type: type,
       brand: brand,
       seats: seats
     }
  end
end

Question

The problem here is that I am duplicating the brand content in both the attribute and typespec.

Given that this information will always be the same, is there a way to have the same functionality but remove the duplication?

2 Likes