如何重载转换

时间:2019-07-02 22:49:05

标签: type-conversion julia overloading

我有两种类型AB。我已经写过B(a::A)convert(::Type{B}, a),但这并不能立即使Array{B}(as::Array{A})工作。我也必须写这种方法吗?根据 the documentation,我希望朱莉娅会替我处理其余的事情。

struct A end
struct B end
B(a::A) = B();
convert(::Type{B}, a) = B(a);

# These work
B(A());
convert(B, A());

# This doesn't
Array{B}([A()]);

这是错误

ERROR: LoadError: MethodError: Cannot `convert` an object of type A to an object of type B
Closest candidates are:
  convert(::Type{T}, !Matched::T) where T at essentials.jl:154
  B(::A) at /home/mvarble/test.jl:3
Stacktrace:
 [1] setindex!(::Array{B,1}, ::A, ::Int64) at ./array.jl:767
 [2] copyto! at ./abstractarray.jl:753 [inlined]
 [3] copyto! at ./abstractarray.jl:745 [inlined]
 [4] Type at ./array.jl:482 [inlined]
 [5] Array{B,N} where N(::Array{A,1}) at ./boot.jl:427
 [6] top-level scope at none:0
 [7] include at ./boot.jl:326 [inlined]
 [8] include_relative(::Module, ::String) at ./loading.jl:1038
 [9] include(::Module, ::String) at ./sysimg.jl:29
 [10] exec_options(::Base.JLOptions) at ./client.jl:267
 [11] _start() at ./client.jl:436

1 个答案:

答案 0 :(得分:3)

您必须从Base向convert添加方法,而不要在当前模块中定义新的convert函数。因此,您应该写:

Base.convert(::Type{B}, a) = B(a)

import Base: convert

在定义convert之前,就像在代码中一样。