我有一个Milkshake类型,其中包含一个flavor字段。我想使用另一种类型Order,该类型仅包含Milkshake的列表。因此,我使用了typealias

julia> VERSION
v"0.5.1"

julia> type Milkshake
           flavor::String
       end

julia> typealias Order Array{Milkshake, 1}
Array{Milkshake,1}

julia> Order([Milkshake("Chocolate"), Milkshake("Vanilla")])
2-element Array{Milkshake,1}:
 Milkshake("Chocolate")
 Milkshake("Vanilla")


不过,我想向Order添加一个构造函数,这样我就可以通过简单地使用flavor字符串来初始化订单。但是,当我尝试定义执行此操作的构造函数时,该定义奇怪地返回类型Array{Milkshake, 1}

julia> Order(milkshakes::String...) = Order(map(Milkshake, milkshakes))
Array{Milkshake,1}


运行时,将产生以下错误。

julia> Order("chocolate", "vanilla")
ERROR: MethodError: Cannot `convert` an object of type Tuple{Milkshake,Milkshake} to an object of type Array{Milkshake,1}
This may have arisen from a call to the constructor Array{Milkshake,1}(...),
since type constructors fall back to convert methods.
 in Array{Milkshake,1}(::String, ::String) at ./REPL[3]:1


如何将该构造函数添加到Order typealias

最佳答案

Order(milkshakes::String...) = Order(map(Milkshake,collect(milkshakes)))有效。

定义后,可以按以下方式构造订单:

julia> Order("Chocolate","Vanilla")
2-element Array{Milkshake,1}:
 Milkshake("Chocolate")
 Milkshake("Vanilla")

10-08 15:56