Identifying traits

The next step is to assign data types to these traits. Conveniently, Julia allows us to bulk-assign traits to an entire subtype tree using the <: operator in the function signature:

# Default behavior is illiquid
LiquidityStyle(::Type) = IsIlliquid()

# Cash is always liquid
LiquidityStyle(::Type{<:Cash}) = IsLiquid()

# Any subtype of Investment is liquid
LiquidityStyle(::Type{<:Investment}) = IsLiquid()

Let's take a look at how we can interpret these three lines of code:

  • We have chosen to make all the types illiquid by default. Note that we could have done this the other way around and made everything liquid by default. This decision is arbitrary and depends on the specific use case.
  • We have chosen to make all the subtypes of Cash liquid, which includes the concrete Money type. The notation of ::Type{<:Cash} indicates all the subtypes of Cash
  • We have chosen to make all the subtypes of Investment liquid. This includes all the subtypes of FixedIncome and Equity, which covers Stock in this example.
You might be wondering why we don't take ::Type{<: Asset} as an argument for the default trait function. Doing so makes it more restrictive as the default value would only be available for types that are defined under the Asset type hierarchy. This may or may not be desirable, depending on how the trait is used. Either way should be fine.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.182.179