Understanding dynamic dispatch

Julia's dispatch mechanism is unique not only because of its multiple dispatch features, but also the way that it treats function arguments dynamically when deciding where to dispatch.

 Let's say we want to randomly pick two objects and check whether they collide. We can define the function as follows:

# randomly pick two things and check
function check_randomly(things)
for i in 1:5
two = rand(things, 2)
collide(two...)
end
end

Let's run it and see what happens:

We can see that different collide methods are called depending on the types of the arguments that are passed in the two variable.

This kind of dynamic behavior can be found as polymorphism in object-oriented programming languages. The main difference is that Julia supports multiple dispatch, utilizing all arguments for dispatch at runtime. By contrast, in Java, only the object being invoked is used for dynamic dispatch. Once the proper class is identified for dispatch, the method arguments are then used for static dispatch when there are several overloaded methods with the same name. 

Multiple dispatch is a powerful feature. When combined with custom data types, it allows the developer to control which methods are called for different scenarios. If you are more interested in multiple dispatch, you can watch a video on YouTube with the title The Unreasonable Effectiveness of Multiple Dispatch. It is a presentation by Stefan Karpinski, recorded at the JuliaCon 2019 conference.

Next, we will look into how function arguments can be parameterized for additional flexibility and expressiveness.

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

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