Concrete class' type method not found error

How do I create a method in a supertype MyModel that uses a datetime method defined on child type?

module M2

    module M1

        export MyModel

        abstract type MyModel end

        Base.isless(x::MyModel, y::MyModel) = datetime(x) < datetime(y)

    end

using .M1

struct MyChild <: MyModel
    datetime
end

datetime(C::MyChild) = C.datetime

MyChild(1) < MyChild(2)

end

ERROR: LoadError: UndefVarError: `datetime` not defined
Stacktrace:
 [1] isless(x::Main.M2.MyChild, y::Main.M2.MyChild)
   @ Main.M2.M1 ~/src/tibra/Tibra.jl/scripts/test_dt.jl:11
 [2] <(x::Main.M2.MyChild, y::Main.M2.MyChild)
   @ Base ./operators.jl:343
 [3] top-level scope
   @ ~/src/tibra/Tibra.jl/scripts/test_dt.jl:21

It says it can’t find the datetime function on the child type.

Try: M1.datetime(C::MyChild) = C.datetime

Since you haven’t imported M1’s function, you are just defining a new function that happens to have the same name.

how would I do it by importing the function if it isn’t defined?

if I do:

import .M1: datetime

WARNING: could not import M1.datetime into M2

and if i do as you say:

ERROR: LoadError: UndefVarError: datetime not defined

I think the solution is to redefine the isless method in the child module

Redefine the same method for base type for use by this module

Base.isless(x::MyModel, y::MyModel) = datetime(x) < datetime(y)

My apologies! I was writing on my phone so I couldn’t test.

module M2
# We need to make sure the datetime function type exists in M2 first
function datetime end
    module M1
        # the bring it into scope of M1
        import ..datetime
        export MyModel

        abstract type MyModel end

        Base.isless(x::MyModel, y::MyModel) = datetime(x) < datetime(y)

    end

using .M1

struct MyChild <: MyModel
    datetime
end

datetime(C::MyChild) = C.datetime

MyChild(1) < MyChild(2)

end

OR if you prefer to have M1 own datetime then

module M2
    module M1
        export MyModel
        function datetime end
        abstract type MyModel end

        Base.isless(x::MyModel, y::MyModel) = datetime(x) < datetime(y)

    end

using .M1

struct MyChild <: MyModel
    datetime
end

M1.datetime(C::MyChild) = C.datetime

MyChild(1) < MyChild(2)

end

Doesn’t work unfortunately.

caused by: MethodError: no method matching datetime(::MyChild)

Which one doesn’t work? Both? Could you give the full stack trace so I can see where it’s erroring? I had it working on my side, so I’m wondering if I copied and pasted it incorrectly or something.