I have a type Milkshake
, which contains a flavor
field. I would like to have another type, Order
, which simply contains a list of Milkshake
s; thus, I used a 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")
I would like to add a constructor to Order
, though, so that I can initialize an order by simply using flavor
strings. However, when I try to define a constructor that does this, the definition oddly returns the type Array{Milkshake, 1}
.
julia> Order(milkshakes::String...) = Order(map(Milkshake, milkshakes))
Array{Milkshake,1}
When run, the following error is produced.
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
How can I add this constructor to the Order
typealias
?
Order(milkshakes::String...) = Order(map(Milkshake,collect(milkshakes)))
works.
With it defined, an Order can be constructed as follows:
julia> Order("Chocolate","Vanilla")
2-element Array{Milkshake,1}:
Milkshake("Chocolate")
Milkshake("Vanilla")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With