Reputation:
Basically I want a module that can use functions that are outside its scope. I need this because my work will only provide a framework where the user will be able to put its own code in. Something like this
Simulation.jl
abstract AbstractType
function startSimulation(unknown::AbstractType)
doStuff(unknown)
end
MyModule.jl
module MyModule
include("Simulation.jl")
export AbstractType, startSimulation
end
SomeImplementation.jl
type ConcreteType <: AbstractType
variable::Int64
end
doStuff(me::ConcreteType)
me.variable
end
and finally Main.jl
# push!(LOAD_PATH, pwd()) # for local usage
using MyModule
include("SomeImplementation.jl")
startSimulation(ConcreteType(5))
Where Simulation.jl and MyModule.jl are written by me and SomeImplementation.jl and Main.jl are written by the user.
Now the above example does not work, because modules have their own namespace and even tho SomeImplementation.jl is imported in main at line 3, the interpreter will not see it in line 4 of Simulation.jl.
I can not import anything in MyModule.jl, because I can not know how the user will name his stuff or what extra libs he might even need.
Is there are way to do this with modules? Otherwise I will just not use modules.
Upvotes: 5
Views: 1065
Reputation: 31342
The answer here is to create stubs for all the functions you want to call within MyModule
as a required interface for the custom subtypes of AbstractType
. That is, within MyModule
, you'd have:
abstract AbstractType
doStuff(::AbstractType) = error("custom AbstractType objects must define a `doStuff` method)
function startSimulation(unknown::AbstractType)
doStuff(unknown)
end
Then the concrete implementations just need to specifically add their doStuff
method to the function in MyModule by importing it or qualifying it:
MyModule.doStuff(me::ConcreteType)
me.variable
end
Upvotes: 10