typesjuliamultiple-dispatch

Union type in Julia


I am wondering about types in Julia, more specific Union. For instance, I have made a function where I add the length of my input a into a vector len_a. If a is of type VariableRefI want the length to be 1. I write it like this;

function add_length!(a::VariableRef,lenComp::Vector, i::Int)

    len_a[i] = 1.0; 
end

However, if a is not of type VariableRef I want it to take the length. So I am wondering if I should do as I have done below, like defining a new type by using Union:

NotVariableRef = Union{Vector, NonlinearExpression, QuadExpr, AffExpr}

function add_length!(a::NotVariableRef,len_a::Vector, i::Int) 

    len_a[i] = length(a)
end

or if I should do it like this;

function add_length!(a::Any,len_a::Vector, i::Int) 

    len_a[i] = length(a)
end

What is the "right" way of doing it? And is this: len_a::Vector, i::Int) alright or should I have something like len_a::Vector{Int}, i::Int64). I am a bit confused by this type system.


Solution

  • Julia is using multiple dispatch to select a particular method to be executed.

    For multiple dispatch among available methods Julia will use the one with the most concrete type. Hence there is no need to define something like NotVariableRef. Normally you would do:

    function add_length!(len_a, a::VariableRef, i)
        len_a[i] = 1.0
    end
    function add_length!(len_a, a, i)
        len_a[i] = length(a)
    end
    

    With this code the appropriate method will be chosen depending on the type of a. Note that by Julia convention I moved the len_a parameter to the front as this is the one being mutated (usually ...! functions mutate the first parameter). I also removed the types as they are not necessary. However if you need I would rather use abstract types for parameters of your function such as AbstractVector and Integer to have a greater API flexibility.