Callable object

Last updated

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

Contents

In different languages

In C++

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

#include<iostream>structFoo{voidoperator()()const{std::cout<<"Called.";}};intmain(){Foofoo_instance;foo_instance();// This will output "Called." to the screen.}

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]

classMinus{publicfunction__invoke($x,$y){return$x-$y;}}$a=array(3,1,4);usort($a,newMinus());

In Python

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

classFoo:def__call__(self):print("Called.")foo_instance=Foo()foo_instance()# This will output "Called." to the screen.

[2]

Another example:

classAccumulator:def__init__(self,n):self.n=ndef__call__(self,x):self.n+=xreturnself.n

In Dart

Callable objects are defined in Dart using the call() method.

classWannabeFunction{call(Stringa,Stringb,Stringc)=>'$a$b$c!';}main(){varwf=newWannabeFunction();varout=wf("Hi","there,","gang");print('$out');}

[3]

In Swift

In Swift, callable objects are defined using callAsFunction. [4]

structCallableStruct{varvalue:IntfunccallAsFunction(_number:Int,scale:Int){print(scale*(number+value))}}letcallable=CallableStruct(value:100)callable(4,scale:2)callable.callAsFunction(4,scale:2)// Both function calls print 208.


Related Research Articles

In programming languages, a closure, also lexical closure or function closure, is a technique for implementing lexically scoped name binding in a language with first-class functions. Operationally, a closure is a record storing a function together with an environment. The environment is a mapping associating each free variable of the function with the value or reference to which the name was bound when the closure was created. Unlike a plain function, a closure allows the function to access those captured variables through the closure's copies of their values or references, even when the function is invoked outside their scope.

In computer programming, lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed. It is a kind of lazy evaluation that refers specifically to the instantiation of objects or other resources.

In object-oriented programming, the decorator pattern is a design pattern that allows behavior to be added to an individual object, dynamically, without affecting the behavior of other instances of the same class. The decorator pattern is often useful for adhering to the Single Responsibility Principle, as it allows functionality to be divided between classes with unique areas of concern as well as to the Open-Closed Principle, by allowing the functionality of a class to be extended without being modified. Decorator use can be more efficient than subclassing, because an object's behavior can be augmented without defining an entirely new object.

In object-oriented (OO) and functional programming, an immutable object is an object whose state cannot be modified after it is created. This is in contrast to a mutable object, which can be modified after it is created. In some cases, an object is considered immutable even if some internally used attributes change, but the object's state appears unchanging from an external point of view. For example, an object that uses memoization to cache the results of expensive computations could still be considered an immutable object.

In mathematics and computer science, a higher-order function (HOF) is a function that does at least one of the following:

In computer science, reflective programming or reflection is the ability of a process to examine, introspect, and modify its own structure and behavior.

In computing, type introspection is the ability of a program to examine the type or properties of an object at runtime. Some programming languages possess this capability.

In computer programming, a function object is a construct allowing an object to be invoked or called as if it were an ordinary function, usually with the same syntax. In some languages, particularly C++, function objects are often called functors.

In some programming languages, eval, short for the English evaluate, is a function which evaluates a string as though it were an expression in the language, and returns a result; in others, it executes multiple lines of code as though they had been included instead of the line including the eval. The input to eval is not necessarily a string; it may be structured representation of code, such as an abstract syntax tree, or of special type such as code. The analog for a statement is exec, which executes a string as if it were a statement; in some languages, such as Python, both are present, while in other languages only one of either eval or exec is.

In compiler construction, name mangling is a technique used to solve various problems caused by the need to resolve unique names for programming entities in many modern programming languages.

In class-based, object-oriented programming, a constructor is a special type of function called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required member variables.

In computer science, a mutator method is a method used to control changes to a variable. They are also widely known as setter methods. Often a setter is accompanied by a getter, which returns the value of the private member variable. They are also known collectively as accessors.

The uniform access principle of computer programming was put forth by Bertrand Meyer. It states "All services offered by a module should be available through a uniform notation, which does not betray whether they are implemented through storage or through computation." This principle applies generally to the syntax of object-oriented programming languages. In simpler form, it states that there should be no syntactical difference between working with an attribute, pre-computed property, or method/query of an object.

this, self, and Me are keywords used in some computer programming languages to refer to the object, class, or other entity which the currently running code is a part of. The entity referred to thus depends on the execution context. Different programming languages use these keywords in slightly different ways. In languages where a keyword like "this" is mandatory, the keyword is the only way to access data and methods stored in the current object. Where optional, these keywords can disambiguate variables and functions with the same name.

A property, in some object-oriented programming languages, is a special sort of class member, intermediate in functionality between a field and a method. The syntax for reading and writing of properties is like for fields, but property reads and writes are (usually) translated to 'getter' and 'setter' method calls. The field-like syntax is easier to read and write than many method calls, yet the interposition of method calls "under the hood" allows for data validation, active updating, or implementation of what may be called "read-only fields".

In computer programming, an anonymous function is a function definition that is not bound to an identifier. Anonymous functions are often arguments being passed to higher-order functions or used for constructing the result of a higher-order function that needs to return a function. If the function is only used once, or a limited number of times, an anonymous function may be syntactically lighter than using a named function. Anonymous functions are ubiquitous in functional programming languages and other languages with first-class functions, where they fulfil the same role for the function type as literals do for other data types.

This article describes the syntax of the C# programming language. The features described are compatible with .NET Framework and Mono.

The syntax and semantics of PHP, a programming language, form a set of rules that define how a PHP program can be written and interpreted.

Swift is a high-level general-purpose, multi-paradigm, compiled programming language created by Chris Lattner in 2010 for Apple Inc. and maintained by the open-source community. Swift compiles to machine code, as it is an LLVM-based compiler. Swift was first released in June 2014, and the Swift toolchain has shipped in Xcode since version 6, released in 2014.

<span class="mw-page-title-main">Strongly typed identifier</span>

A strongly typed identifier is user-defined data type which serves as an identifier or key that is strongly typed. This is a solution to the "primitive obsession" code smell as mentioned by Martin Fowler. The data type should preferably be immutable if possible. It is common for implementations to handle equality testing, serialization and model binding.

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.
  4. "Declarations — The Swift Programming Language (Swift 5.6)". docs.swift.org. Retrieved 2022-02-28.