Designing parametric types

To simplify this design, we can parameterize the type of the thing being traded. What is the thing? We can leverage the abstract type here. The supertype of Stock is Equity, while the supertype of Equity is Investment. Since we want to keep the code generic and buying/selling investment products is similar, we can choose to accept any type that is a subtype of Investment:

struct SingleTrade{T <: Investment} <: Trade
type::LongShort
instrument::T
quantity::Int
price::Float64
end

Now, we have defined a new type called SingleTrade, where the underlying instrument has a type, T, where T can be any subtype of Investment. At this point, we can create trades with different kinds of instruments:

These objects actually have different types—SingleTrade{Stock} and SingleTrade{StockOption}. How do they relate to each other? They are also subtypes of SingleTrade, as shown in the following screenshot:

Since both types are subtypes of SingleTrade, this allows us to define functions that apply to both types, as we will see in the next section.

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

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