Custom Inspect
An Opaque type can control the output of Str.inspect being called on itself by implementing to_inspect.
This can be useful for more complex types, or to hide internal implementation details.
Simple Tag Union
Color := [ Red, Green, Blue, ].{ to_inspect : Color -> Str to_inspect = |color| { match color { Red => "_RED_" Green => "_GREEN_" Blue => "_BLUE_" } } } expect Str.inspect(Color.(Red)) == "_RED_" expect Str.inspect(Color.(Green)) == "_GREEN_" expect Str.inspect(Color.(Blue)) == "_BLUE_"
Redacting a Secret
CreditCard :: Str.{ create = |nb| CreditCard.(nb) to_inspect : CreditCard -> Str to_inspect = |CreditCard.(nb)| { last_four_digits = nb.to_utf8().take_last(4) |> Str.from_utf8 ?? "****" # Note: do not use this default in production. If your credit card string cannot be converted to utf8 you should fail loudly. "**** **** **** ${last_four_digits}" } } expect Str.inspect(CreditCard.("1111 2222 3333 1234")) == "**** **** **** 1234"
Output
Run the tests from the directory that has OpaqueTypes.roc in it:
$ roc test OpaqueTypes.roc All (4) tests passed.
The tests check the custom color names and the redacted credit card number.
Validated with Roc nightly-2026-10-27-de79a0f.