Is there a way I could force type-checking during Struct creation instead of waiting for a method call to enforce a spec?
Here’s a bit of sample code:
r = %Range{first: 1, last: "ok"} # I would like this to explode
Enum.count(range) # explodes here
# the following will explode immediately
r = 1.."ok"
For reference purposes, here are links to the code for Enum.count and Range:
- Range: https://github.com/elixir-lang/elixir/blob/master/lib/elixir/lib/range.ex#L12
- Enum: https://github.com/elixir-lang/elixir/blob/master/lib/elixir/lib/enum.ex#L492
While I don’t necessarily need Range
itself to explode upon instantiation if I pass an invalid value, I would like to be able to enforce this kind of type safety on custom structs, so for example:
defmodule MyNum do
defstruct first: 0, second: 0
@typedoc """
Type that represents Examples struct with :first as integer and :last as integer.
"""
@type t :: %MyNum{first: integer, second: integer}
end
defmodule Adder do
@spec add(MyNum.t) :: integer
def add(my_num) do
my_num.first + my_num.second
end
end
Given the above code, I’d like num = %MyNum{ first: "ok" }
to explode immediately rather than wait until I invoke a function (in this case, Adder.add/1
)