Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I build a parameterless constructor for a parametric type in an outer constructor?

Tags:

julia

In order to instantiate a type like x = MyType{Int}()

I can define a inner constructor.

immutable MyType{T}
    x::Vector{T}

    MyType() = new(T[])
end

Is it possible to achieve the same objective using an outer constructor?

like image 359
colinfang Avatar asked Nov 09 '22 02:11

colinfang


1 Answers

This can be done using the following syntax:

(::Type{MyType{T}}){T}() = MyType{T}(T[])

The thing in the first set of parentheses describes the called object. ::T means "of type T", so this is a definition for calling an object of type Type{MyType{T}}, which means the object MyType{T} itself. Next {T} means that T is a parameter of this definition, and a value for it must be available in order to call this definition. So MyType{Int} matches, but MyType doesn't. From there on, the syntax should be familiar.

This syntax is definitely a bit fiddly and unintuitive, and we hope to improve it in a future version of the language, hopefully v0.6.

like image 161
Jeff Bezanson Avatar answered Nov 15 '22 06:11

Jeff Bezanson