Julia Methods
A method is a version of a function written for one specific type of argument. Julia picks the method that matches the type of the value you pass.
A function written for a struct type
The annotation p::Person makes this function a method for Person values. It returns the age plus one.
struct Person
name::String
age::Int
end
birthday(p::Person) = p.age + 1
p = Person("Ana", 31)
println(birthday(p))Methods live outside the struct
The struct above holds only its fields. The greet method is defined after the struct block and still works on Person values.
struct Person
name::String
age::Int
end
greet(p::Person) = "Hello, " * p.name
p = Person("Ana", 31)
println(greet(p))A second method for another type
The label function below has two methods, one for Person and one for Dog. Each call picks the method matching its argument's type.
struct Person
name::String
age::Int
end
struct Dog
name::String
age::Int
end
label(p::Person) = "person: " * p.name
label(d::Dog) = "dog: " * d.name
println(label(Person("Ana", 31)))
println(label(Dog("Rex", 4)))Example
struct Person
name::String
age::Int
end
struct Dog
name::String
age::Int
end
introduce(p::Person) = "I am " * p.name
introduce(d::Dog) = d.name * " says woof"
println(introduce(Person("Ana", 31)))
println(introduce(Dog("Rex", 4)))Key points
- Typed argument: p::Person in a function definition limits that version to Person values.
- Method: one typed version of a function, such as birthday(p::Person).
- Outside: methods are written outside the struct block, anywhere after the type is defined.
- Same name: several methods can share one function name, one per argument type.
- Choice: Julia picks the method by the type of the argument at the call.
In this example, introduce has two methods, one for Person and one for Dog. The first call passes a Person, so the Person method builds the greeting from the name field. The second call passes a Dog, so the Dog method runs instead.
Note
adding a method for a new type never changes the methods written for other types.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
Where is a method for the Person type written?