Julia: Understanding Multiple dispatch for OOP

417 views Asked by At

Lets say I have the following types:

type cat
  cry:: String
  legs:: Int
  fur:: String
end


type car
  noise::String
  wheels::Int
  speed::Int
end


Lion = cat("meow", 4, "fuzzy")
vw = car("honk", 4, 45)

And I want to add a method describe to both of them which prints the data inside them. Is it best to use methods to do it this way:

describe(a::cat) = println("Type: Cat"), println("Cry:", a.cry, " Legs:",a.legs,  " fur:", a.fur);
describe(a::car) = println("Type: Car"), println("Noise:", a.noise, " Wheels:", a.wheels, " Speed:", a.speed)

describe(Lion)
describe(vw)

Output:

Type: Cat
Cry:meow Legs:4 fur:fuzzy
Type: Car
Noise:honk Wheels:4 Speed:45

Or should I use a function like in this question I posted before: Julia: What is the best way to set up a OOP model for a library

Which method is more efficient?

Most Methods examples in the documentation are simple functions, if I wanted a more complex Method with loops or if statements are they possible?

1

There are 1 answers

0
IainDunning On BEST ANSWER

First of all, I recommend using a capital letter as the first letter of a type name - this is an extremely consistent thing in Julia style, so not doing it would definitely be awkward for people using your code.

As you are doing multi-statement methods, you should probably write them as full functions, e.g.

function describe(a::cat)
  println("Type: Cat")
  println("Cry:", a.cry, " Legs:", a.legs,  " fur:", a.fur)
end
function describe(a::car)
  println("Type: Car")
  println("Noise:", a.noise, " Wheels:", a.wheels, " Speed:", a.speed)
end

Typically the one-liner version is used only for simple single statements.

May also be worth noting that we are making one function, with two methods, in case that wasn't clear from the manual.

Finally, you could also add a method to the base Julia print function, e.g.

function Base.print(io::IO, a::cat)
  println(io, "Type: Cat")
  print(io, "Cry:", a.cry, " Legs:", a.legs,  " fur:", a.fur)
end
function Base.print(io::IO, a::car)
  println(io, "Type: Car")
  print(io, "Noise:", a.noise, " Wheels:", a.wheels, " Speed:", a.speed)
end

(if you call println, it'll call print internally and add the \n automatically)