call
call(x, args...)
If x is not a Function, then x(args...) is equivalent to call(x, args...). This means that function-like behavior can be added to any type by defining new call methods.
Examples
-
Call a function with arguments:
julia> function add_numbers(a, b) return a + b end julia> call(add_numbers, 5, 3) 8In this example, the
callfunction is used to invoke theadd_numbersfunction with arguments5and3. It returns the sum of the two numbers. -
Call a function-like object:
julia> struct MultiplyByTwo value::Int end julia> (m::MultiplyByTwo)(x) = m.value * x julia> m = MultiplyByTwo(5) julia> call(m, 3) 15Here, the
callfunction is used to invoke the function-like behavior of theMultiplyByTwoobject. Thecallmethod defined forMultiplyByTwomultiplies the object'svaluefield with the argumentx. - Handle non-function objects:
julia> x = 10 julia> call(x, "Hello, world!") ERROR: MethodError: objects of type Int64 are not callableIf the provided
xis not a function or a function-like object, an error will be thrown. In this example, callingcallwith an integerxresults in aMethodErrorbecause integers are not callable.
Common mistake example:
julia> call(5, 3)
ERROR: MethodError: objects of type Int64 are not callable
In this example, the mistake is passing an integer 5 as the first argument to call. Since integers are not callable, a MethodError is thrown. Make sure to pass a callable object or a function as the first argument to call.
See Also
User Contributed Notes
Add a Note
The format of note supported is markdown, use triple backtick to start and end a code block.