How to add constructor to type alias in Julia?

I have a type Milkshakethat contains a field flavor. I would like to have another type Orderthat just contains a list of Milkshakes; that way i used 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, to initialize the order, just using the lines flavor. However, when I try to define a constructor that does this, the definition strangely returns a type Array{Milkshake, 1}.

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

The following error is generated at startup.

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 to add this constructor to Order typealias?

+4
source share
1 answer

Order(milkshakes::String...) = Order(map(Milkshake,collect(milkshakes))) works.

:

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

Source: https://habr.com/ru/post/1673219/


All Articles