Methods in Julia
Julia supports methods defined on struct types.
struct Rect
width::Int
height::Int
end
# This `area` method is defined for the `Rect` type.
function area(r::Rect)
return r.width * r.height
end
# Methods can be defined for either mutable or immutable types.
# Here's an example of a method for the immutable `Rect` type.
function perim(r::Rect)
return 2*r.width + 2*r.height
end
function main()
r = Rect(10, 5)
# Here we call the 2 methods defined for our struct.
println("area: ", area(r))
println("perim:", perim(r))
# Julia automatically handles method dispatch based on the type of the argument.
# There's no need for explicit pointer or reference syntax.
println("area: ", area(r))
println("perim:", perim(r))
end
main()
To run the program:
$ julia methods.jl
area: 50
perim: 30
area: 50
perim: 30
In Julia, methods are defined outside of the struct definition, unlike some object-oriented languages. The first argument of a method is conventionally named self
or the first letter of the type name (like r
for Rect
), and it determines which type the method is associated with.
Julia uses multiple dispatch, which means that methods are chosen based on the types of all their arguments, not just the first. This is more flexible than single dispatch used in many object-oriented languages.
In Julia, there’s no distinction between value and reference types in method calls. The language handles this automatically, and the syntax is the same whether you’re working with values or references.
Next, we’ll look at Julia’s mechanism for grouping and naming related sets of methods: abstract types and interfaces.