Jump to content

Callable object

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by 212.123.218.234 (talk) at 12:40, 25 March 2019 ("Callable class in Dart" is added). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

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

In different languages

In C++

std::function is a template class that can hold any callable object that matches its signature.

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) { return $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 {
    public function __invoke($x, $y) { return $x - $y; }
}

$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.

# Python 3 Syntax
class Foo(object):
    def __call__(self):
        print("Called.")

foo_instance = Foo()
foo_instance()  # This will output "Called." to the screen.

[2]

Another example:

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

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

Dart

To allow your Dart class to be called like a function, implement the call() method.

class WannabeFunction {
  call(String a, String b, String c) => '$a $b $c!';
}

main() {
  var wf = new WannabeFunction();
  var out = wf("Hi","there,","gang");
  print('$out');
}

[3]

References

  1. ^ PHP Documentation on Magic Methods
  2. ^ Bösch, Florian. "What is a "callable" in Python?". StackOverflow.com. Retrieved 24 September 2017.
  3. ^ "A Tour of the Dart Language". www.dartlang.org. Retrieved 2019-03-25.