Renato Melo
Renato Melo

Reputation: 184

Julia Union of Composite Types: `convert` has no method matching convert

I'm trying to do a Union between two composite types that I've created:

type point
   x::Int8
   y::Int8
end

type vector
    x::Int8
    y::Int8
end

VecOrPoint = Union{point,vector}

x = point(Int8(2),Int8(3))
y = vector(Int8(2),Int8(3))

function sum(u::VecOrPoint,v::VecOrPoint)
  return  VecOrPoint(u.x + v.x,u.y + v.y) # ERROR HERE
end


z = sum(x,y)

And i'm getting the folowing error:

ERROR: LoadError: MethodError: `convert` has no method matching    

convert(::Type{Union{point,vector}}, ::Int8, ::Int8)

This may have arisen from a call to the constructor Union{point,vector}  (...),

since type constructors fall back to convert methods.

Closest candidates are:
call{T}(::Type{T}, ::Any)
convert{T}(::Type{T}, !Matched::T)

in sum at /home/renatinho/periodoAtual/recsys/testeJulia.jl:17

while loading /home/renatinho/periodoAtual/recsys/testeJulia.jl, in 

expression starting on line 20

I've serched on Google but i cannot figure out anything

Upvotes: 1

Views: 635

Answers (1)

Michael Ohlrogge
Michael Ohlrogge

Reputation: 10990

From the Julia documentation

A type union is a special abstract type

and from here:

Abstract types cannot be instantiated

Thus, what you are trying to do is not possible. (when you call VecOrPoint() in your function, you are trying to create an instantiation, i.e. trying to create an object whose type is your union of types).

I also don't really understand the purpose behind what you are trying to do. What could it mean to "convert" something to a union of types, when the types within that union are different? (In your example you give, the two types are identical, so I suppose it could be possible in that very limited sense, but it also wouldn't make any sense to have two identical types like that and then take the union of them).

If you wanted to accomplish something along those lines, you could perhaps write yourself a new Myconvert() function (or possibly overload the existing convert function). In your new function, you could perform some logic on the input, and based on that, convert it to one or the other of your types. Your new function then could sensibly take as an input your union of types.

Edit: or, as Chris suggests in comments, use a type dispatch. See also Dan's comment to original post for another useful idea.

Upvotes: 3

Related Questions