Enforcing type consistency in using parameters 

One of the most useful features with type parameters is that they can be used to enforce type consistency.

Let's say we want to create a new function that groups two Thing objects together. As we don't really care about what concrete types are passed, we can just write a single function that does the work:

function group_anything(A::Thing, B::Thing)
println("Grouped ", A, " and ", B)
end

We can also run some trivial tests quickly to ensure that all four combinations of spaceships and asteroids are working:

You may wonder how we get such a nice output regarding the specific weapons. As we have learned previously, we can extend the show function from the Base package with our types. You can find our implementation of the show function in the book's GitHub repository.

Now, all is good, but then we realize that the requirement is slightly different from what we thought originally. Rather than grouping any kind of object, the function should be able to group the same kinds of objects only—that is, it's okay to group spaceship with spaceship and asteroid with asteroid, but not spaceship with asteroid. So what can we do here? An easy solution is to just throw a type parameter in the method signature:

function group_same_things(A::T, B::T) where {T <: Thing}
println("Grouped ", A, " and ", B)
end

In this function, we have annotated both arguments with type T, and we specify that T must be a subtype of Thing. Because both arguments use the same type, we are now instructing the system to dispatch to this method only if both arguments have the same type. We can now try the same four test cases as before, as shown in the following code:

Effectively, we can now ensure that the method is only dispatched when the arguments have the same type. This is one of the few reasons why it is a good idea to use type parameters for function arguments.

Next, we will talk about another reason to use type parameters—extracting type information from the method signature.

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

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