我有一个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
?
答案 0 :(得分:4)
Order(milkshakes::String...) = Order(map(Milkshake,collect(milkshakes)))
有效。
定义它后,可以按如下方式构建订单:
julia> Order("Chocolate","Vanilla")
2-element Array{Milkshake,1}:
Milkshake("Chocolate")
Milkshake("Vanilla")