Multiple Dispatch: Field Access Problem

I’m sure questions like this have been asked before, but I couldn’t find them. I was testing out Crystal’s multiple dispatch (comparing it to Julia’s) with the following piece of code, but I’m getting undefined method 'name' for Dog for the encounter function.

Is Crystal unable to do multiple dispatch when fields are involved?

abstract class Pet; end

class Dog < Pet
    def initialize(@name : String); end 
end 

class Cat < Pet
    def initialize(@name : String); end 
end 

def meets(a : Dog, b : Dog) 
    return "licks"
end 

def meets(a : Dog, b : Cat) 
    return "chases"
end 

def meets(a : Cat, b : Dog) 
    return "hisses"
end 

def meets(a : Cat, b : Cat) 
    return "slinks"
end 

def encounter(a : Pet, b : Pet)
    p "#{a.name} meets #{b.name} and #{meets(a, b)}"
end

fido = Dog.new "Fido"
bingo = Dog.new "Bingo"
sam = Cat.new "Sam"

encounter(fido, bingo)
encounter(fido, sam)

You just haven’d defined a name method. The initializer only assigns a value to the instance variable @name, but that does not automatically generate a method by that name (you can access the ivar as dog.@name though).
Use getter name for this, which expands to def name; @name; end and exposes the ivar as a method.

1 Like

Just noticed that. Thanks. I’m still learning the syntax.

This is actually a great example of how abstract works in Crystal, thanks.