Auto promote or convert

Hi guys,
I am looking for a way to do the following:

julia> type DD
           x::Int
       end

julia> type EE
           x::Int
       end
julia> function f(a::EE)
           println(a.x)
       end
f (generic function with 1 method)

julia> t = DD(5)
DD(5)

julia> f(t)
ERROR: MethodError: no method matching f(::DD)
Closest candidates are:
  f(::EE) at REPL[4]:2

I want t which is type of DD to be converted to type EE version automatically . What should i do for that?
Thanks

Strictly speaking, fully “automatic” promotion it is not possible because of the design of the language:
https://docs.julialang.org/en/latest/manual/conversion-and-promotion/

You should write a method for f that takes DD if you want to use this syntax.

You can not do that, since you define your function only for ::EE it will only accept that. You can either just drop ::EE and the function will work for both DD and EE since they have the same field name x, or just define a constructor EE(a::DD) = EE(a.x) and call f like f(EE(t)).

1 Like