Abstract methods: pattern

I want to create a “module general” which provides an abstract type (fruit), to be subtyped in another “module specific”. In the “module general”, I want to provide operations on fruit in general, but which hae to rely on methods specific for the concrete type.

 module general
     export fruit,weights
     abstract type fruit end
     function weight end
     weights(fruits) = [weight(fruit) for fruit in fruits]
 end
 module specific
     using general
     export apple,lemon,weight
     struct apple <: fruit
         taste
     end
     weight(f::apple)=0.2
     struct lemon <: fruit
         taste
     end
     weight(f::lemon)=0.1
 end
 using general,specific
 weights([apple(:delicious),lemon(:bitter)])

As must be expected, this does not work: in “module general” the weight methods are undefined. The example is simplistic, and provides no reason why I would like to keep things in separate modules, I must ask you to take this as a given.

Is there any way I can, together, with the definition of an abstract class in “module general” provide functions that rely on using methods specific to subtypes, to be defined in another module? Or is that not the Julian way?

:grinning:

Yes, that’s possible and widely used. You should explicitly add methods to general.weight:

general.weight(::apple)=0.2
general.weight(::lemon)=0.1

It is also possible to import general.weight into specific’s namespace, but that’s not recommended in order to avoid unintentional overloads.

Also, please follow the naming guidelines to make your code easier to read for others.

1 Like

Vot tak, konietshno! I should have thought about it, that what “import” is all about.
Thanks a lot, Vasily! And I will read the naming guidelines.

1 Like