Callable object explained

See also: Function object.

A callable object, in computer programming, is any object that can be called like a function.

In different languages

In C++

In C++, any class that overloads the function call operator operator may be called using function-call syntax.

  1. include

struct Foo

int main

In C#

In PHP

PHP 5.3+ has first-class functions that can be used e.g. as parameter to the usort function:

$a = array(3, 1, 4);usort($a, function ($x, $y));

It is also possible in PHP 5.3+ to make objects invokable by adding a magic __invoke method to their class:[1]

class Minus

$a = array(3, 1, 4);usort($a, new Minus);

In Python

In Python any object with a __call__ method can be called using function-call syntax.

class Foo: def __call__(self): print("Called.")

foo_instance = Foofoo_instance # This will output "Called." to the screen.[2]

Another example:class Accumulator: def __init__(self, n): self.n = n

def __call__(self, x): self.n += x return self.n

In Dart

Callable objects are defined in Dart using the call method.class WannabeFunction

main [3]

In Swift

In Swift, callable objects are defined using callAsFunction.[4] struct CallableStruct let callable = CallableStruct(value: 100)callable(4, scale: 2)callable.callAsFunction(4, scale: 2)// Both function calls print 208.

External links

Notes and References

  1. http://php.net/manual/en/language.oop5.magic.php#object.invoke PHP Documentation on Magic Methods
  2. Web site: Bösch. Florian. What is a "callable" in Python?. StackOverflow.com. 24 September 2017.
  3. Web site: A Tour of the Dart Language. www.dartlang.org. 2019-03-25.
  4. Web site: Declarations — The Swift Programming Language (Swift 5.6) . 2022-02-28 . docs.swift.org.