Parametric function return type

raythurnevoid
Sat, 02 Sep 2023 02:15:13 +0000
New to Julia

I wanted to create a function that takes in input a callback and can return its result while being able to tell Julia what’s going to be the return type (since the Function type is not parametric).

This is the skeleton at the moment:

function call_cb_if_needed(::Type{T}, cb::Function)::T where {T<:Any}
    # if some_condition
    #   return some_value
    # else
    return cb()
end

call_cb_if_needed(Int, () -> 3)
# 3

This is a paradigm I’m taking with me from JS, I don’t know whether there’s a better way to achieve the same in Julia, but the fact that you can define a parametric Type as an argument of the function looks like it is not documented anywhere, thus I wanted to share it here for anyone that may find this useful.

Suggestions are welcome!

9 posts - 4 participants