The holy traits pattern configures a Julia type with capabilities that guide generic behavior. A trait is an ability or characteristic: collection traits such as IteratorSize tell iteration machinery how to build results efficiently. section 12.5.1
For collection types, the pattern works through trait types and dispatch:
- Define a trait method for the collection type, such as IteratorSize(::Type{<:Rocket}) = Base.SizeUnknown(). section 12.5.1
- Represent trait values with concrete subtypes; HasLength and SizeUnknown are subtypes of IteratorSize. section 12.5.1
- Let generic operations dispatch on traits: collect considers IteratorEltype and IteratorSize, using length for HasLength or a growing array for SizeUnknown. section 12.5.1
A staged rocket with an unknown size
After defining iteration for Rocket subtypes, assign SizeUnknown to the family with IteratorSize(::Type{<:Rocket}) = Base.SizeUnknown(). Generic collection operations can then work with the type, while map(mass, booster) returns the masses of its three stages and sum(thrust, booster) computes total thrust.
