Is it possible to build a constructor without parameters for a parametric type in an external constructor?

To create an instance of type x = MyType{Int}()

I can define an internal constructor.

 immutable MyType{T} x::Vector{T} MyType() = new(T[]) end 

Is it possible to achieve the same goal using an external constructor?

+5
source share
3 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 "type T", so this is the definition for calling an object of type Type{MyType{T}} , which means the object MyType{T} . The following {T} means that T is a parameter of this definition, and a value for it must be available to call this definition. So MyType{Int} consistent, but MyType not. From there, the syntax should be familiar.

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

+1
source

Maybe I'm wrong, but if you cannot create a parameterless function, for example:

 julia> f{T}() = show(T) WARNING: static parameter T does not occur in signature for f at none:1. The method will not be callable. f (generic function with 1 method) 

therefore, you cannot do this:

 julia> immutable MyType{T} x::Vector{T} end julia> MyType{T}() = MyType{T}(T[]) WARNING: static parameter T does not occur in signature for call at none:1. The method will not be callable. MyType{T} julia> x = MyType{Int}() ERROR: MethodError: `convert` has no method matching convert(::Type{MyType{Int64}}) ... 

Each external constructor is also a function.

0
source

you can say

 f(T::Type) = show(T) 

and

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

But julia needs to see the type of call to find out what you want.

0
source

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


All Articles