Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a constructor to a type alias in Julia?

I have a type Milkshake, which contains a flavor field. I would like to have another type, Order, which simply contains a list of Milkshakes; 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?

like image 883
Harrison Grodin Avatar asked Mar 26 '17 07:03

Harrison Grodin


1 Answers

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")  
like image 132
Dan Getz Avatar answered Oct 30 '22 19:10

Dan Getz