Implementing the holy traits pattern

To illustrate the concept of this pattern, we will implement some functions for the personal asset data types that we developed in Chapter 2Modules, Packages, and Data Type Concepts. As you may recall, the abstract types for the asset type hierarchy are defined as follows:

abstract type Asset end

abstract type Property <: Asset end
abstract type Investment <: Asset end
abstract type Cash <: Asset end

abstract type House <: Property end
abstract type Apartment <: Property end

abstract type FixedIncome <: Investment end
abstract type Equity <: Investment end

The Asset type is at the top of the hierarchy and has the Property, Investment, and Cash subtypes. At the next level, House and Apartment are subtypes of Property, while FixedIncome and Equity are subtypes of Investment.

Now, let's define some concrete types:

struct Residence <: House
location
end

struct Stock <: Equity
symbol
name
end

struct TreasuryBill <: FixedIncome
cusip
end

struct Money <: Cash
currency
amount
end

What do we have here? Let's take a look at these concepts in more detail:

  • Residence is a house that someone lives in and has a location. 
  • Stock is an equity investment, and it is identified by a trading symbol and the name of the company. 
  • TreasuryBill is a short-term government-issued form of security in the United States, and it is defined with a standard identifier called CUSIP.
  • Money is just cash, but we want to store the currency and respective amount here.

Note that we have not annotated the types for the fields because they aren't important for illustrating the trait concept here.

..................Content has been hidden....................

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