implicit conversions with user defined types?

Viewed 62

With the following code:

import Base.convert

abstract type MySequential end

struct MyFiniteSequence{T} <: MySequential
       vec::NTuple{N,T} where N
end

Base.convert(MyFiniteSequence, r) = MyFiniteSequence{typeof(r)}((r,))

Now try:

julia> convert(MyFiniteSequence, 1)
MyFiniteSequence{Int64}((1,))

So far so good. Now try to do an implict conversion:

julia> MyFiniteSequence(1)
ERROR: MethodError: no method matching MyFiniteSequence(::Int64)
Closest candidates are:
  MyFiniteSequence(::Tuple{Vararg{T,N}} where N) where T at REPL[2]:2
Stacktrace:
 [1] top-level scope at REPL[5]:1

I think there is a problem because of the {T, N} annotations, but am unsure how the syntax of convert needs to be changed. Is there a way to define convert to get the implicit conversion from Int to struct?

1 Answers

I believe implicit constructor calls to convert were removed in the transition from julia 0.7 to 1.0. But you can just define a constructor that calls convert if that's what you want:

julia> MyFiniteSequence(x) = Base.convert(MyFiniteSequence, x)
MyFiniteSequence

julia> MyFiniteSequence(1)
MyFiniteSequence{Int64}((1,))
Related