invoke
invoke(f, (types...), args...)
Invoke a method for the given generic function matching the specified types (as a tuple), on the specified arguments. The arguments must be compatible with the specified types. This allows invoking a method other than the most specific matching method, which is useful when the behavior of a more general definition is explicitly needed (often as part of the implementation of a more specific method of the same function).
Examples
-
Invoke a method on a generic function:
julia> f(x::Int, y::Int) = x + y julia> invoke(f, (Int, Int), 2, 3) 5This example invokes the method
fwith arguments2and3, matching the typesIntandInt. -
Invoke a more general definition of a method:
julia> f(x::Number, y::Number) = x * y julia> invoke(f, (Int, Int), 2, 3) 6In this case,
invokeis used to explicitly invoke the methodfwith the typesIntandInt, even though there is a more specific matching method available. The more general definition offis called, which multiplies the arguments. - Invoke a method with compatible argument types:
julia> f(x::String, y::String) = x * y julia> invoke(f, (AbstractString, AbstractString), "Hello", "World") "HelloWorld"The
invokefunction allows invoking a method with compatible argument types. In this example,fis invoked withAbstractStringtypes, which includesString. The method concatenates the two strings.
Common mistake example:
julia> f(x::Int, y::Int) = x + y
julia> invoke(f, (Int, Int), "2", 3)
ERROR: MethodError: no method matching f(::String, ::Int64)
In this example, the argument types provided to invoke do not match the method definition. It's important to ensure that the arguments are compatible with the specified types to avoid such errors.
See Also
assert, backtrace, code_llvm, code_lowered, code_native, code_typed, code_warntype, :@which, compilecache, current_module, eval, finalize, finalizer, fullname, function_module, function_name, include_dependency, InterruptException, invoke, isconst, isdefined, isgeneric, methodswith, method_exists, module_name, module_parent, require, subtypes, unsafe_load, workspace, __precompile__,User Contributed Notes
Add a Note
The format of note supported is markdown, use triple backtick to start and end a code block.