Methods

Recall from Functions that a function is an object that maps a tuple of arguments to a return value, or throws an exception if no appropriate value can be returned. It is common for the same conceptual function or operation to be implemented quite differently for different types of arguments: adding two integers is very different from adding two floating-point numbers, both of which are distinct from adding an integer to a floating-point number. Despite their implementation differences, these operations all fall under the general concept of “addition”. Accordingly, in Julia, these behaviors all belong to a single object: the + function.

To facilitate using many different implementations of the same concept smoothly, functions need not be defined all at once, but can rather be defined piecewise by providing specific behaviors for certain combinations of argument types and counts. A definition of one possible behavior for a function is called a method. Thus far, we have presented only examples of functions defined with a single method, applicable to all types of arguments. However, the signatures of method definitions can be annotated to indicate the types of arguments in addition to their number, and more than a single method definition may be provided. When a function is applied to a particular tuple of arguments, the most specific method applicable to those arguments is applied. Thus, the overall behavior of a function is a patchwork of the behaviors of its various method definitions. If the patchwork is well designed, even though the implementations of the methods may be quite different, the outward behavior of the function will appear seamless and consistent.

The choice of which method to execute when a function is applied is called dispatch. Julia allows the dispatch process to choose which of a function’s methods to call based on the number of arguments given, and on the types of all of the function’s arguments. This is different than traditional object-oriented languages, where dispatch occurs based only on the first argument, which often has a special argument syntax, and is sometimes implied rather than explicitly written as an argument. [1] Using all of a function’s arguments to choose which method should be invoked, rather than just the first, is known as multiple dispatch. Multiple dispatch is particularly useful for mathematical code, where it makes little sense to artificially deem the operations to “belong” to one argument more than any of the others: does the addition operation in x+y belong to x any more than it does to y? The implementation of a mathematical operator generally depends on the types of all of its arguments. Even beyond mathematical operations, however, multiple dispatch ends up being a powerful and convenient paradigm for structuring and organizing programs.

[1]In C++ or Java, for example, in a method call like obj.meth(arg1,arg2), the object obj “receives” the method call and is implicitly passed to the method via the this keyword, rather than as an explicit method argument. When the current this object is the receiver of a method call, it can be omitted altogether, writing just meth(arg1,arg2), with this implied as the receiving object.

Defining Methods

Until now, we have, in our examples, defined only functions with a single method having unconstrained argument types. Such functions behave just like they would in traditional dynamically typed languages. Nevertheless, we have used multiple dispatch and methods almost continually without being aware of it: all of Julia’s standard functions and operators, like the aforementioned + function, have many methods defining their behavior over various possible combinations of argument type and count.

When defining a function, one can optionally constrain the types of parameters it is applicable to, using the :: type-assertion operator, introduced in the section on Composite Types:

julia>f(x::Float64,y::Float64)=2x+y;

This function definition applies only to calls where x and y are both values of type Float64:

julia>f(2.0,3.0)7.0

Applying it to any other types of arguments will result in a MethodError:

julia>f(2.0,3)ERROR:MethodError:`f`hasnomethodmatchingf(::Float64,::Int64)Closestcandidatesare:f(::Float64,!Matched::Float64)julia>f(Float32(2.0),3.0)ERROR:MethodError:`f`hasnomethodmatchingf(::Float32,::Float64)Closestcandidatesare:f(!Matched::Float64,::Float64)julia>f(2.0,"3.0")ERROR:MethodError:`f`hasnomethodmatchingf(::Float64,::ASCIIString)Closestcandidatesare:f(::Float64,!Matched::Float64)julia>f("2.0","3.0")ERROR:MethodError:`f`hasnomethodmatchingf(::ASCIIString,::ASCIIString)

As you can see, the arguments must be precisely of type Float64. Other numeric types, such as integers or 32-bit floating-point values, are not automatically converted to 64-bit floating-point, nor are strings parsed as numbers. Because Float64 is a concrete type and concrete types cannot be subclassed in Julia, such a definition can only be applied to arguments that are exactly of type Float64. It may often be useful, however, to write more general methods where the declared parameter types are abstract:

julia>f(x::Number,y::Number)=2x-y;julia>f(2.0,3)1.0

This method definition applies to any pair of arguments that are instances of Number. They need not be of the same type, so long as they are each numeric values. The problem of handling disparate numeric types is delegated to the arithmetic operations in the expression 2x-y.

To define a function with multiple methods, one simply defines the function multiple times, with different numbers and types of arguments. The first method definition for a function creates the function object, and subsequent method definitions add new methods to the existing function object. The most specific method definition matching the number and types of the arguments will be executed when the function is applied. Thus, the two method definitions above, taken together, define the behavior for f over all pairs of instances of the abstract type Number — but with a different behavior specific to pairs of Float64 values. If one of the arguments is a 64-bit float but the other one is not, then the f(Float64,Float64) method cannot be called and the more general f(Number,Number) method must be used:

julia>f(2.0,3.0)7.0julia>f(2,3.0)1.0julia>f(2.0,3)1.0julia>f(2,3)1

The 2x+y definition is only used in the first case, while the 2x-y definition is used in the others. No automatic casting or conversion of function arguments is ever performed: all conversion in Julia is non-magical and completely explicit. Conversion and Promotion, however, shows how clever application of sufficiently advanced technology can be indistinguishable from magic. [Clarke61]

For non-numeric values, and for fewer or more than two arguments, the function f remains undefined, and applying it will still result in a MethodError:

julia>f("foo",3)ERROR:MethodError:`f`hasnomethodmatchingf(::ASCIIString,::Int64)Closestcandidatesare:f(!Matched::Number,::Number)julia>f()ERROR:MethodError:`f`hasnomethodmatchingf()

You can easily see which methods exist for a function by entering the function object itself in an interactive session:

julia>ff(genericfunction with2methods)

This output tells us that f is a function object with two methods. To find out what the signatures of those methods are, use the methods() function:

julia>methods(f)# 2 methods for generic function "f":f(x::Float64,y::Float64)atnone:1f(x::Number,y::Number)atnone:1

which shows that f has two methods, one taking two Float64 arguments and one taking arguments of type Number. It also indicates the file and line number where the methods were defined: because these methods were defined at the REPL, we get the apparent line number none:1.

In the absence of a type declaration with ::, the type of a method parameter is Any by default, meaning that it is unconstrained since all values in Julia are instances of the abstract type Any. Thus, we can define a catch-all method for f like so:

julia>f(x,y)=println("Whoa there, Nelly.");julia>f("foo",1)Whoathere,Nelly.

This catch-all is less specific than any other possible method definition for a pair of parameter values, so it is only be called on pairs of arguments to which no other method definition applies.

Although it seems a simple concept, multiple dispatch on the types of values is perhaps the single most powerful and central feature of the Julia language. Core operations typically have dozens of methods:

julia>methods(+)# 139 methods for generic function "+":+(x::Bool)atbool.jl:33+(x::Bool,y::Bool)atbool.jl:36+(y::AbstractFloat,x::Bool)atbool.jl:46+(x::Int64,y::Int64)atint.jl:14+(x::Int8,y::Int8)atint.jl:14+(x::UInt8,y::UInt8)atint.jl:14+(x::Int16,y::Int16)atint.jl:14+(x::UInt16,y::UInt16)atint.jl:14+(x::Int32,y::Int32)atint.jl:14+(x::UInt32,y::UInt32)atint.jl:14+(x::UInt64,y::UInt64)atint.jl:14+(x::Int128,y::Int128)atint.jl:14+(x::UInt128,y::UInt128)atint.jl:14+(x::Float32,y::Float32)atfloat.jl:192+(x::Float64,y::Float64)atfloat.jl:193+(z::Complex{T<:Real},w::Complex{T<:Real})atcomplex.jl:96+(x::Real,z::Complex{T<:Real})atcomplex.jl:106+(z::Complex{T<:Real},x::Real)atcomplex.jl:107+(x::Rational{T<:Integer},y::Rational{T<:Integer})atrational.jl:167+(a::Float16,b::Float16)atfloat16.jl:136+(x::Base.GMP.BigInt,y::Base.GMP.BigInt)atgmp.jl:243+(a::Base.GMP.BigInt,b::Base.GMP.BigInt,c::Base.GMP.BigInt)atgmp.jl:266+(a::Base.GMP.BigInt,b::Base.GMP.BigInt,c::Base.GMP.BigInt,d::Base.GMP.BigInt)atgmp.jl:272+(a::Base.GMP.BigInt,b::Base.GMP.BigInt,c::Base.GMP.BigInt,d::Base.GMP.BigInt,e::Base.GMP.BigInt)atgmp.jl:279+(x::Base.GMP.BigInt,c::Union{UInt32,UInt16,UInt8,UInt64})atgmp.jl:291+(c::Union{UInt32,UInt16,UInt8,UInt64},x::Base.GMP.BigInt)atgmp.jl:295+(x::Base.GMP.BigInt,c::Union{Int16,Int32,Int8,Int64})atgmp.jl:307+(c::Union{Int16,Int32,Int8,Int64},x::Base.GMP.BigInt)atgmp.jl:308+(x::Base.MPFR.BigFloat,y::Base.MPFR.BigFloat)atmpfr.jl:206+(x::Base.MPFR.BigFloat,c::Union{UInt32,UInt16,UInt8,UInt64})atmpfr.jl:213+(c::Union{UInt32,UInt16,UInt8,UInt64},x::Base.MPFR.BigFloat)atmpfr.jl:217+(x::Base.MPFR.BigFloat,c::Union{Int16,Int32,Int8,Int64})atmpfr.jl:221+(c::Union{Int16,Int32,Int8,Int64},x::Base.MPFR.BigFloat)atmpfr.jl:225+(x::Base.MPFR.BigFloat,c::Union{Float16,Float64,Float32})atmpfr.jl:229+(c::Union{Float16,Float64,Float32},x::Base.MPFR.BigFloat)atmpfr.jl:233+(x::Base.MPFR.BigFloat,c::Base.GMP.BigInt)atmpfr.jl:237+(c::Base.GMP.BigInt,x::Base.MPFR.BigFloat)atmpfr.jl:241+(a::Base.MPFR.BigFloat,b::Base.MPFR.BigFloat,c::Base.MPFR.BigFloat)atmpfr.jl:318+(a::Base.MPFR.BigFloat,b::Base.MPFR.BigFloat,c::Base.MPFR.BigFloat,d::Base.MPFR.BigFloat)atmpfr.jl:324+(a::Base.MPFR.BigFloat,b::Base.MPFR.BigFloat,c::Base.MPFR.BigFloat,d::Base.MPFR.BigFloat,e::Base.MPFR.BigFloat)atmpfr.jl:331+(x::Irrational{sym},y::Irrational{sym})atconstants.jl:71+{T<:Number}(x::T<:Number,y::T<:Number)atpromotion.jl:205+{T<:AbstractFloat}(x::Bool,y::T<:AbstractFloat)atbool.jl:43+(x::Number,y::Number)atpromotion.jl:167+(x::Integer,y::Ptr{T})atpointer.jl:70+(x::Bool,A::AbstractArray{Bool,N})atarray.jl:829+(x::Integer,y::Char)atchar.jl:41+(x::Number)atoperators.jl:72+(r1::OrdinalRange{T,S},r2::OrdinalRange{T,S})atoperators.jl:325+{T<:AbstractFloat}(r1::FloatRange{T<:AbstractFloat},r2::FloatRange{T<:AbstractFloat})atoperators.jl:331+(r1::FloatRange{T<:AbstractFloat},r2::FloatRange{T<:AbstractFloat})atoperators.jl:348+(r1::FloatRange{T<:AbstractFloat},r2::OrdinalRange{T,S})atoperators.jl:349+(r1::OrdinalRange{T,S},r2::FloatRange{T<:AbstractFloat})atoperators.jl:350+(x::Ptr{T},y::Integer)atpointer.jl:68+{S,T}(A::Range{S},B::Range{T})atarray.jl:773+{S,T}(A::Range{S},B::AbstractArray{T,N})atarray.jl:791+(A::AbstractArray{Bool,N},x::Bool)atarray.jl:828+(A::BitArray{N},B::BitArray{N})atbitarray.jl:926+(A::Union{DenseArray{Bool,N},SubArray{Bool,N,A<:DenseArray{T,N},I<:Tuple{Vararg{Union{Colon,Range{Int64},Int64}}},LD}},B::Union{DenseArray{Bool,N},SubArray{Bool,N,A<:DenseArray{T,N},I<:Tuple{Vararg{Union{Colon,Range{Int64},Int64}}},LD}})atarray.jl:859+(A::Base.LinAlg.SymTridiagonal{T},B::Base.LinAlg.SymTridiagonal{T})atlinalg/tridiag.jl:59+(A::Base.LinAlg.Tridiagonal{T},B::Base.LinAlg.Tridiagonal{T})atlinalg/tridiag.jl:254+(A::Base.LinAlg.Tridiagonal{T},B::Base.LinAlg.SymTridiagonal{T})atlinalg/special.jl:113+(A::Base.LinAlg.SymTridiagonal{T},B::Base.LinAlg.Tridiagonal{T})atlinalg/special.jl:112+(A::Base.LinAlg.UpperTriangular{T,S<:AbstractArray{T,2}},B::Base.LinAlg.UpperTriangular{T,S<:AbstractArray{T,2}})atlinalg/triangular.jl:164+(A::Base.LinAlg.LowerTriangular{T,S<:AbstractArray{T,2}},B::Base.LinAlg.LowerTriangular{T,S<:AbstractArray{T,2}})atlinalg/triangular.jl:165+(A::Base.LinAlg.UpperTriangular{T,S<:AbstractArray{T,2}},B::Base.LinAlg.UnitUpperTriangular{T,S<:AbstractArray{T,2}})atlinalg/triangular.jl:166+(A::Base.LinAlg.LowerTriangular{T,S<:AbstractArray{T,2}},B::Base.LinAlg.UnitLowerTriangular{T,S<:AbstractArray{T,2}})atlinalg/triangular.jl:167+(A::Base.LinAlg.UnitUpperTriangular{T,S<:AbstractArray{T,2}},B::Base.LinAlg.UpperTriangular{T,S<:AbstractArray{T,2}})atlinalg/triangular.jl:168+(A::Base.LinAlg.UnitLowerTriangular{T,S<:AbstractArray{T,2}},B::Base.LinAlg.LowerTriangular{T,S<:AbstractArray{T,2}})atlinalg/triangular.jl:169+(A::Base.LinAlg.UnitUpperTriangular{T,S<:AbstractArray{T,2}},B::Base.LinAlg.UnitUpperTriangular{T,S<:AbstractArray{T,2}})atlinalg/triangular.jl:170+(A::Base.LinAlg.UnitLowerTriangular{T,S<:AbstractArray{T,2}},B::Base.LinAlg.UnitLowerTriangular{T,S<:AbstractArray{T,2}})atlinalg/triangular.jl:171+(A::Base.LinAlg.AbstractTriangular{T,S<:AbstractArray{T,2}},B::Base.LinAlg.AbstractTriangular{T,S<:AbstractArray{T,2}})atlinalg/triangular.jl:172+(Da::Base.LinAlg.Diagonal{T},Db::Base.LinAlg.Diagonal{T})atlinalg/diagonal.jl:50+(A::Base.LinAlg.Bidiagonal{T},B::Base.LinAlg.Bidiagonal{T})atlinalg/bidiag.jl:111+{T}(B::BitArray{2},J::Base.LinAlg.UniformScaling{T})atlinalg/uniformscaling.jl:28+(A::Base.LinAlg.Diagonal{T},B::Base.LinAlg.Bidiagonal{T})atlinalg/special.jl:103+(A::Base.LinAlg.Bidiagonal{T},B::Base.LinAlg.Diagonal{T})atlinalg/special.jl:104+(A::Base.LinAlg.Diagonal{T},B::Base.LinAlg.Tridiagonal{T})atlinalg/special.jl:103+(A::Base.LinAlg.Tridiagonal{T},B::Base.LinAlg.Diagonal{T})atlinalg/special.jl:104+(A::Base.LinAlg.Diagonal{T},B::Array{T,2})atlinalg/special.jl:103+(A::Array{T,2},B::Base.LinAlg.Diagonal{T})atlinalg/special.jl:104+(A::Base.LinAlg.Bidiagonal{T},B::Base.LinAlg.Tridiagonal{T})atlinalg/special.jl:103+(A::Base.LinAlg.Tridiagonal{T},B::Base.LinAlg.Bidiagonal{T})atlinalg/special.jl:104+(A::Base.LinAlg.Bidiagonal{T},B::Array{T,2})atlinalg/special.jl:103+(A::Array{T,2},B::Base.LinAlg.Bidiagonal{T})atlinalg/special.jl:104+(A::Base.LinAlg.Tridiagonal{T},B::Array{T,2})atlinalg/special.jl:103+(A::Array{T,2},B::Base.LinAlg.Tridiagonal{T})atlinalg/special.jl:104+(A::Base.LinAlg.SymTridiagonal{T},B::Array{T,2})atlinalg/special.jl:112+(A::Array{T,2},B::Base.LinAlg.SymTridiagonal{T})atlinalg/special.jl:113+(A::Base.LinAlg.Diagonal{T},B::Base.LinAlg.SymTridiagonal{T})atlinalg/special.jl:121+(A::Base.LinAlg.SymTridiagonal{T},B::Base.LinAlg.Diagonal{T})atlinalg/special.jl:122+(A::Base.LinAlg.Bidiagonal{T},B::Base.LinAlg.SymTridiagonal{T})atlinalg/special.jl:121+(A::Base.LinAlg.SymTridiagonal{T},B::Base.LinAlg.Bidiagonal{T})atlinalg/special.jl:122+{Tv1,Ti1,Tv2,Ti2}(A_1::Base.SparseMatrix.SparseMatrixCSC{Tv1,Ti1},A_2::Base.SparseMatrix.SparseMatrixCSC{Tv2,Ti2})atsparse/sparsematrix.jl:873+(A::Base.SparseMatrix.SparseMatrixCSC{Tv,Ti<:Integer},B::Array{T,N})atsparse/sparsematrix.jl:885+(A::Array{T,N},B::Base.SparseMatrix.SparseMatrixCSC{Tv,Ti<:Integer})atsparse/sparsematrix.jl:887+{P<:Base.Dates.Period}(Y::Union{SubArray{P<:Base.Dates.Period,N,A<:DenseArray{T,N},I<:Tuple{Vararg{Union{Colon,Range{Int64},Int64}}},LD},DenseArray{P<:Base.Dates.Period,N}},x::P<:Base.Dates.Period)atdates/periods.jl:50+{T<:Base.Dates.TimeType}(r::Range{T<:Base.Dates.TimeType},x::Base.Dates.Period)atdates/ranges.jl:39+{T<:Number}(x::AbstractArray{T<:Number,N})atabstractarray.jl:442+{S,T}(A::AbstractArray{S,N},B::Range{T})atarray.jl:782+{S,T}(A::AbstractArray{S,N},B::AbstractArray{T,N})atarray.jl:800+(A::AbstractArray{T,N},x::Number)atarray.jl:832+(x::Number,A::AbstractArray{T,N})atarray.jl:833+(x::Char,y::Integer)atchar.jl:40+{N}(index1::Base.IteratorsMD.CartesianIndex{N},index2::Base.IteratorsMD.CartesianIndex{N})atmultidimensional.jl:121+(J1::Base.LinAlg.UniformScaling{T<:Number},J2::Base.LinAlg.UniformScaling{T<:Number})atlinalg/uniformscaling.jl:27+(J::Base.LinAlg.UniformScaling{T<:Number},B::BitArray{2})atlinalg/uniformscaling.jl:29+(J::Base.LinAlg.UniformScaling{T<:Number},A::AbstractArray{T,2})atlinalg/uniformscaling.jl:30+(J::Base.LinAlg.UniformScaling{T<:Number},x::Number)atlinalg/uniformscaling.jl:31+(x::Number,J::Base.LinAlg.UniformScaling{T<:Number})atlinalg/uniformscaling.jl:32+{TA,TJ}(A::AbstractArray{TA,2},J::Base.LinAlg.UniformScaling{TJ})atlinalg/uniformscaling.jl:35+{T}(a::Base.Pkg.Resolve.VersionWeights.HierarchicalValue{T},b::Base.Pkg.Resolve.VersionWeights.HierarchicalValue{T})atpkg/resolve/versionweight.jl:21+(a::Base.Pkg.Resolve.VersionWeights.VWPreBuildItem,b::Base.Pkg.Resolve.VersionWeights.VWPreBuildItem)atpkg/resolve/versionweight.jl:83+(a::Base.Pkg.Resolve.VersionWeights.VWPreBuild,b::Base.Pkg.Resolve.VersionWeights.VWPreBuild)atpkg/resolve/versionweight.jl:129+(a::Base.Pkg.Resolve.VersionWeights.VersionWeight,b::Base.Pkg.Resolve.VersionWeights.VersionWeight)atpkg/resolve/versionweight.jl:183+(a::Base.Pkg.Resolve.MaxSum.FieldValues.FieldValue,b::Base.Pkg.Resolve.MaxSum.FieldValues.FieldValue)atpkg/resolve/fieldvalue.jl:43+{P<:Base.Dates.Period}(x::P<:Base.Dates.Period,y::P<:Base.Dates.Period)atdates/periods.jl:43+{P<:Base.Dates.Period}(x::P<:Base.Dates.Period,Y::Union{SubArray{P<:Base.Dates.Period,N,A<:DenseArray{T,N},I<:Tuple{Vararg{Union{Colon,Range{Int64},Int64}}},LD},DenseArray{P<:Base.Dates.Period,N}})atdates/periods.jl:49+(x::Base.Dates.Period,y::Base.Dates.Period)atdates/periods.jl:196+(x::Base.Dates.CompoundPeriod,y::Base.Dates.Period)atdates/periods.jl:197+(y::Base.Dates.Period,x::Base.Dates.CompoundPeriod)atdates/periods.jl:198+(x::Base.Dates.CompoundPeriod,y::Base.Dates.CompoundPeriod)atdates/periods.jl:199+(dt::Base.Dates.DateTime,y::Base.Dates.Year)atdates/arithmetic.jl:13+(dt::Base.Dates.Date,y::Base.Dates.Year)atdates/arithmetic.jl:17+(dt::Base.Dates.DateTime,z::Base.Dates.Month)atdates/arithmetic.jl:37+(dt::Base.Dates.Date,z::Base.Dates.Month)atdates/arithmetic.jl:43+(x::Base.Dates.Date,y::Base.Dates.Week)atdates/arithmetic.jl:60+(x::Base.Dates.Date,y::Base.Dates.Day)atdates/arithmetic.jl:62+(x::Base.Dates.DateTime,y::Base.Dates.Period)atdates/arithmetic.jl:64+(a::Base.Dates.TimeType,b::Base.Dates.Period,c::Base.Dates.Period)atdates/periods.jl:210+(a::Base.Dates.TimeType,b::Base.Dates.Period,c::Base.Dates.Period,d::Base.Dates.Period...)atdates/periods.jl:212+(x::Base.Dates.TimeType,y::Base.Dates.CompoundPeriod)atdates/periods.jl:216+(x::Base.Dates.CompoundPeriod,y::Base.Dates.TimeType)atdates/periods.jl:221+(x::Base.Dates.Instant)atdates/arithmetic.jl:4+(x::Base.Dates.TimeType)atdates/arithmetic.jl:8+(y::Base.Dates.Period,x::Base.Dates.TimeType)atdates/arithmetic.jl:66+{T<:Base.Dates.TimeType}(x::Base.Dates.Period,r::Range{T<:Base.Dates.TimeType})atdates/ranges.jl:40+(a,b,c)atoperators.jl:83+(a,b,c,xs...)atoperators.jl:84

Multiple dispatch together with the flexible parametric type system give Julia its ability to abstractly express high-level algorithms decoupled from implementation details, yet generate efficient, specialized code to handle each case at run time.

Method Ambiguities

It is possible to define a set of function methods such that there is no unique most specific method applicable to some combinations of arguments:

julia>g(x::Float64,y)=2x+y;julia>g(x,y::Float64)=x+2y;WARNING:Newdefinitiong(Any,Float64)atnone:1isambiguouswith:g(Float64,Any)atnone:1.Tofix,defineg(Float64,Float64)beforethenewdefinition.julia>g(2.0,3)7.0julia>g(2,3.0)8.0julia>g(2.0,3.0)7.0

Here the call g(2.0,3.0) could be handled by either the g(Float64,Any) or the g(Any,Float64) method, and neither is more specific than the other. In such cases, Julia warns you about this ambiguity, but allows you to proceed, arbitrarily picking a method. You should avoid method ambiguities by specifying an appropriate method for the intersection case:

julia>g(x::Float64,y::Float64)=2x+2y;julia>g(x::Float64,y)=2x+y;julia>g(x,y::Float64)=x+2y;julia>g(2.0,3)7.0julia>g(2,3.0)8.0julia>g(2.0,3.0)10.0

To suppress Julia’s warning, the disambiguating method must be defined first, since otherwise the ambiguity exists, if transiently, until the more specific method is defined.

Parametric Methods

Method definitions can optionally have type parameters immediately after the method name and before the parameter tuple:

julia>same_type{T}(x::T,y::T)=true;julia>same_type(x,y)=false;

The first method applies whenever both arguments are of the same concrete type, regardless of what type that is, while the second method acts as a catch-all, covering all other cases. Thus, overall, this defines a boolean function that checks whether its two arguments are of the same type:

julia>same_type(1,2)truejulia>same_type(1,2.0)falsejulia>same_type(1.0,2.0)truejulia>same_type("foo",2.0)falsejulia>same_type("foo","bar")truejulia>same_type(Int32(1),Int64(2))false

This kind of definition of function behavior by dispatch is quite common — idiomatic, even — in Julia. Method type parameters are not restricted to being used as the types of parameters: they can be used anywhere a value would be in the signature of the function or body of the function. Here’s an example where the method type parameter T is used as the type parameter to the parametric type Vector{T} in the method signature:

julia>myappend{T}(v::Vector{T},x::T)=[v...,x]myappend(genericfunction with1method)julia>myappend([1,2,3],4)4-elementArray{Int64,1}:1234julia>myappend([1,2,3],2.5)ERROR:MethodError:`myappend`hasnomethodmatchingmyappend(::Array{Int64,1},::Float64)Closestcandidatesare:myappend{T}(::Array{T,1},!Matched::T)julia>myappend([1.0,2.0,3.0],4.0)4-elementArray{Float64,1}:1.02.03.04.0julia>myappend([1.0,2.0,3.0],4)ERROR:MethodError:`myappend`hasnomethodmatchingmyappend(::Array{Float64,1},::Int64)Closestcandidatesare:myappend{T}(::Array{T,1},!Matched::T)

As you can see, the type of the appended element must match the element type of the vector it is appended to, or else a MethodError is raised. In the following example, the method type parameter T is used as the return value:

julia>mytypeof{T}(x::T)=Tmytypeof(genericfunction with1method)julia>mytypeof(1)Int64julia>mytypeof(1.0)Float64

Just as you can put subtype constraints on type parameters in type declarations (see Parametric Types), you can also constrain type parameters of methods:

same_type_numeric{T<:Number}(x::T,y::T)=truesame_type_numeric(x::Number,y::Number)=falsejulia>same_type_numeric(1,2)truejulia>same_type_numeric(1,2.0)falsejulia>same_type_numeric(1.0,2.0)truejulia>same_type_numeric("foo",2.0)nomethodsame_type_numeric(ASCIIString,Float64)julia>same_type_numeric("foo","bar")nomethodsame_type_numeric(ASCIIString,ASCIIString)julia>same_type_numeric(Int32(1),Int64(2))false

The same_type_numeric function behaves much like the same_type function defined above, but is only defined for pairs of numbers.

Note on Optional and keyword Arguments

As mentioned briefly in Functions, optional arguments are implemented as syntax for multiple method definitions. For example, this definition:

f(a=1,b=2)=a+2b

translates to the following three methods:

f(a,b)=a+2bf(a)=f(a,2)f()=f(1,2)

This means that calling f() is equivalent to calling f(1,2). In this case the result is 5, because f(1,2) invokes the first method of f above. However, this need not always be the case. If you define a fourth method that is more specialized for integers:

f(a::Int,b::Int)=a-2b

then the result of both f() and f(1,2) is -3. In other words, optional arguments are tied to a function, not to any specific method of that function. It depends on the types of the optional arguments which method is invoked. When optional arguments are defined in terms of a global variable, the type of the optional argument may even change at run-time.

Keyword arguments behave quite differently from ordinary positional arguments. In particular, they do not participate in method dispatch. Methods are dispatched based only on positional arguments, with keyword arguments processed after the matching method is identified.

Call overloading and function-like objects

For any arbitrary Julia object x other than Function objects (defined via function syntax), x(args...) is equivalent to call(x,args...), where call() is a generic function in the Julia Base module. By adding new methods to call, you can add a function-call syntax to arbitrary Julia types. (Such “callable” objects are sometimes called “functors.”)

For example, if you want to make x(arg) equivalent to x*arg for x::Number, you can define:

Base.call(x::Number,arg)=x*arg

at which point you can do:

x=7x(10)

to get 70.

call overloading is also used extensively for type constructors in Julia, discussed later in the manual.

Empty generic functions

Occasionally it is useful to introduce a generic function without yet adding methods. This can be used to separate interface definitions from implementations. It might also be done for the purpose of documentation or code readability. The syntax for this is an empty function block without a tuple of arguments:

function emptyfuncend
[Clarke61]Arthur C. Clarke, Profiles of the Future (1961): Clarke’s Third Law.