Array of Functions type matching

I have an array of functions. If I try to pass that array to another function that has the parameter type of Array{Function, 1}, I get a type mismatch error. Here is a working example.

function test()
    return function()
        return rand(10)
    end 
end
arr = [test() for i in 1:3]

function test2(arr::Array{Function, 1})
    println([x() for x in arr])
end

julia> test2(arr)
ERROR: MethodError: no method matching test2(::Array{var"#103#104",1})
Closest candidates are:
  test2(!Matched::Array{Function,1}) at none:1
Stacktrace:
 [1] top-level scope at none:1
 [2] run_repl(::REPL.AbstractREPL, ::Any) at /build/julia/src/julia-1.5.4/usr/share/julia/stdlib/v1.5/REPL/src/REPL.jl:288

julia> arr isa Array{Function, 1}
false

julia> arr[1] isa Function
true

Why is this happening?

Every function has it’s own type, so typeof(arr) is Vector{typeof(test)). If you define function test2(arr::Vector{<:Function}), everything will work (although if you have an array of different functions, it will be type unstable).

1 Like