Pluto.jl - How do I dispatch to a subtype created in a notebook?

I created a small package called ProblematicAnimals.jl to demonstrate a problem I’m having with Pluto.jl notebooks. I sincerely hope a solution to this can be found.

Defined outside of Pluto

abstract type AbstractAnimal end
struct Cat <: AbstractAnimal end
sound(cat::Cat) = "meow"
why(a::AbstractAnimal) = sound(a)

It should work like this.

julia> cat = Cat()
Cat()

julia> sound(cat)
"meow"

julia> why(cat)
"meow"

Simple.

However, I can’t get a subtype defined in a notebook to work.

From inside Pluto.jl:

struct Pig <: AbstractAnimal end

sound(pig::Pig) = "oink"

pig = Pig()

sound(pig) # "oink"

why(pig) # The `sound(pig::Pig)` function is invisible to the why(a) function.
  • How can I get why(pig) to work in a Pluto.jl notebook?
  • I’ve provided a notebook that you can try for yourself in Pluto.jl to see the problem yourself.

The problem is the definition of the method sound in the notebook. See this section of the manual: Modules · The Julia Language

The code in the linked notebook defines a new function Main.sound rather than implementing a new method for ProblematicAnimals.sound. You have two choices to fix it, the easiest is to fully qualify the name when defining the new method.

ProblematicAnimals.sound(pig::Pig) = "oink"

The other is to import that method as described in the manual in the block at the top of the notebook.

2 Likes

Thank you so much. That was a nice Christmas present.