Ash Union Calculations

I'm still wrapping my head around polymorphic relationships and was wondering why a calculation on one needs to return a %Ash.Union{}? E.g.
def calculate(records, _, _) do
Enum.map(records, fn record ->
cond do
record.checking_account ->
%Ash.Union{type: :checking_account, value: record.checking_account}

record.savings_account ->
%Ash.Union{type: :savings_account, value: record.savings_account}

true ->
nil
end
end)
end
def calculate(records, _, _) do
Enum.map(records, fn record ->
cond do
record.checking_account ->
%Ash.Union{type: :checking_account, value: record.checking_account}

record.savings_account ->
%Ash.Union{type: :savings_account, value: record.savings_account}

true ->
nil
end
end)
end
I tried swapping out the return values above for the direct value, e.g. record.checking_account and that seemed to work, so what value is being added / what function is this playing here? I don't have multiple clauses in my condition yet as I'm still building things out (if that makes a difference). What was also surprising about this is that despite the calculation specifying a union type in the second argument (e.g. AccountImplementation), it was happy to return just the value. Thanks.
Solution:
We don't check that calculation return values match their declaration (for performance reasons)
Jump to solution
5 Replies
Solution
ZachDaniel
ZachDaniel•2w ago
We don't check that calculation return values match their declaration (for performance reasons)
ZachDaniel
ZachDaniel•2w ago
Any instance of a union is wrapped in %Ash.Union{} Other things might break down the line by not returning a value matching the type
Songyun
SongyunOP•2w ago
Does that mean the type declaration is for documentation purposes?
ZachDaniel
ZachDaniel•2w ago
for calculation returns and generic action returns, effectively yes its used for code generation etc. as well i.e for types displayed in APIs we could theoretically validate those values at runtime, but its not really realistic to do. Once the type system releases, we ought to be able to do more on that front 🙂
Songyun
SongyunOP•2w ago
Very good info, thank you!

Did you find this page helpful?