vonpetersenn
vonpetersenn

Reputation: 1

Can not specify Custom Type in Julia Project across Modules without running into MethodError

I'm encountering a MethodError when trying to use a custom type across multiple modules in Julia. The error occurs because the type is loaded in different places, causing Julia to treat them as distinct types. I'm looking for a solution to define and use my custom type consistently across the project.

Here a minimal example:

I have the project structure

root
--main.jl    
--MyModule.jl
--ArgsType.jl  

The MyType.jl defines a struct that I want to use throughout the project e.g. some arguments:

module ArgsType

export AbstractArgs, Args

abstract type AbstractArgs end

Base.@kwdef mutable struct Args <: AbstractArgs
    a::Bool = true
end

end

The MyModule.jl handels my function:

module MyModule

include("ArgsType.jl")
using .ArgsType: AbstractArgs

export my_function

function my_function(args::T) where T <: AbstractArgs
    if args.a
        println("Hello, World!")
    end
end

end

In the main.jl script, I controll what I want to do by creating an Args object and parse it to the functions from the loaded MyModule:

include("ArgsType.jl")
include("MyModule.jl")

using .ArgsType: Args
using .MyModule: my_function

args = Args()
my_function(args)

This will result in a MethodError since we loaded the ArgsType module in two different places.

ERROR: MethodError: no method matching my_function(::Args)

Closest candidates are:
  my_function(::T) where T<:Main.MyModule.ArgsType.AbstractArgs
   @ Main.MyModule c:\Users\Paulo\Documents\Coding Projekte\julia_custom_typing\MyModule.jl:8

Stacktrace:
 [1] top-level scope
   @ c:\Users\Paulo\Documents\Coding Projekte\julia_custom_typing\main.jl:8

What would be a solution to this problem? How can I define a Type such that I do not run into this problem?

I don't see any way to define custom types without running into the problem of having the neccessity of loading them in each module where I define a function that I want to specify to use that type.

Upvotes: 0

Views: 26

Answers (0)

Related Questions