liveBook · Manning

Holy traits pattern

As explained in Julia as a Second Language

The holy traits pattern is a Julia design pattern that exposes an object's capabilities through trait types or trait-returning methods.

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.

How Julia as a Second Language covers it

How deep it goes
Explains trait types, concrete trait values, dispatch, and defaults through IteratorSize, stopping short of a general trait catalog.
Examples
Uses staged rockets, IteratorSize, collect, map over rocket mass, and sum over rocket thrust.
What it assumes
Assumes familiarity with Julia collections and iteration while introducing traits through the IteratorSize example.
What you can do after
Apply it via Julia collection interfaces to make custom data types work with prebuilt collection functions.
How it connects
Connects traits with multiple dispatch, iteration, abstract types, and collection interfaces.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Julia as a Second Language. The section links point to the parts of the book it draws on.