Working with parametric abstract types

Abstract types can be enhanced in the same way that composite types can be parameterized. Let's continue with the preceding example. Suppose that we want to build an abstract type called Holding that keeps track of a P type that is used by its subtypes. We can code it as follows:

abstract type Holding{P} end

Then, every subtype of Holding{P} must also take a  P type parameter. As an example, we can create two new types —StockHolding3{T,P} and CashHolding{P}:

struct StockHolding3{T, P} <: Holding{P}

stock::Stock
quantity::T
price::P
marketvalue::P
end

struct CashHolding{P} <: Holding{P}
currency::String
amount::P
marketvalue::P
end

We can examine how these types are related as follows:

Let's create a new StockHolding3 object:

As expected, the certificate_in_the_safe object is a subtype of Holding{Float64}.

Note that, when a type is parameterized, each variation is considered as a separate type that is unrelated to the others, except that they have a common supertype. As an example, Holding{Int} is a different type from Holding{Float64}, but they are both subtypes of Holding. Let's quickly prove this to ourselves:

 

In summary, Julia comes with a very rich type system that a programmer can use to reason how each type relates to other types. Abstract types allow us to define behaviors in a hierarchy of relationships, and concrete types are used to define how data is stored. Parametric types are used to extend existing types to variations of field types. All of these language constructs allow the programmer to model data and behavior effectively.

Next, we will look into data type conversions and how they apply to functions.

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

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