Doing strange things with DataTypes in functions

Hey all :slight_smile:

Initially I wanted to do this:

julia> f{T}(i::T) = i
ERROR: UndefVarError: T not defined
Stacktrace:
 [1] top-level scope
   @ REPL[51]:1

But it only works for constructor of structs.

Then I thought I could do that:

julia> f(T::DataType, i::T) = i
ERROR: UndefVarError: T not defined
Stacktrace:
 [1] top-level scope
   @ REPL[50]:1

But that also doesn’t work.

(I know that I don’t need to specify the datatype but I want for better readability)

Does anyone know how to do that?

That’s what I want :smiley:

f(::Type{T}, i::T) where T = i

Why not simply f(i::T) where T = i ?

(Assuming you want to use the value T in your function body…)

That’s the actual structure. (Var names changed…)

function some_name(
    ::Type{T},
    counter::Int, 
    initial_bars::Vector{Dict{OtherType,T}},
    dict_name::Dict{OtherType, MyType},
)::Dict{OtherType,T} where T

The first argument seems redundant, I think you get the same functionality with the following?

function some_name(
    counter::Int, 
    initial_bars::Vector{Dict{OtherType,T}},
    dict_name::Dict{OtherType, MyType},
)::Dict{OtherType,T} where T

That’s true. But the T is a bit hidden. The first arg is only for readability :slight_smile: