Common constructors for subtypes of abstract type

I have a type AbstractT, and for each subtype I want to define a constructor T(x::Tuple), but I canโ€™t find a general way to do this, because everyone in Julia, like this, uses send, but I canโ€™t send a constructor, since the name of the constructor matches the type, and therefore each constructor is a different function. that is, it would work if it were

construct{T<:AbstractT}(::Type{T},x::Tuple) = # Define all the constructors

and I do it internally, but then it doesnโ€™t work very well with other packages that will directly cause T (x) and errors. Is Julia using a send under the hood in some way that I could click on?

+6
source share
1 answer

, ! :

julia> abstract type AbstractT end

julia> struct ConcreteT{T} <: AbstractT; end

julia> (::Type{ConcreteT{Int}})() = 1

julia> (::Type{ConcreteT{Float64}})() = 2

julia> ConcreteT{Int}()
1

julia> ConcreteT{Float64}()
2

... :

julia> (::Type{ConcreteT{T}})() where {T<:Number} = 3


julia> (::Type{ConcreteT{T}})() where {T<:AbstractArray} = 4

julia> ConcreteT{Float32}()
3

julia> ConcreteT{UnitRange{Int}}()
4

, :

julia> (::Type{T})() where {T<:AbstractT} = 5

julia> ConcreteT{String}()
ConcreteT{String}()

julia> AbstractT()
5

ConcreteT{String}? , ... , :

julia> methods(ConcreteT{String})
# 2 methods for type constructor:
[1] (::Type{ConcreteT{T}})() where T in Main at REPL[2]:1
[2] (::Type{T})() where T<:AbstractT in Main at REPL[12]:1

; , :

julia> (::Type{T})(x) where {T<:AbstractT} = x

julia> ConcreteT{String}(6)
6

julia> ConcreteT{Int}(7)
7
+9

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


All Articles