Best practice to handle type annotations

Then you’ll need to make provisions to specify it manually. Something like

julia> function func(::Type{T}, n::Integer) where T
           y = complex(T)[]
           for k = 1:n
               push!(y, exp(im * pi / k))
               # EDIT: see comments below regarding doing the calculation with the target type
           end
           return y
       end
func (generic function with 1 method)

julia> func(Float16, 8)
8-element Vector{ComplexF16}:
  Float16(-1.0) + Float16(0.0)im
   Float16(0.0) + Float16(1.0)im
   Float16(0.5) + Float16(0.866)im
 Float16(0.707) + Float16(0.707)im
 Float16(0.809) + Float16(0.588)im
 Float16(0.866) + Float16(0.5)im
 Float16(0.901) + Float16(0.4338)im
 Float16(0.924) + Float16(0.3826)im

(You could alternatively use function func(T::Type, n::Integer) for the definition, but there can sometimes be performance differences between these for complicated reasons including but not limited to this.)

3 Likes