*** Welcome to piglix ***

Duck typing


In computer programming, duck typing is an application of the duck test in type safety. It requires that type checking be deferred to runtime, and is implemented by means of dynamic typing or reflection.

Duck typing is concerned with establishing the suitability of an object for some purpose. With normal typing, suitability is assumed to be determined by an object's type only. In duck typing, an object's suitability is determined by the presence of certain methods and properties (with appropriate meaning), rather than the actual type of the object.

Consider the following pseudo-code for a duck-typed language:

In the example, each time the calculate function is called, objects without related inheritance may be used (numbers, lists and strings). As long as the objects support the "+" and "*" methods, the operation will succeed. If translated to Ruby or Python, for example, the result of the code would be:

Thus, duck typing can work the same as polymorphism, but without inheritance. The only restriction that function calculate places on its arguments is that they implement the "+" and "*" methods.

The duck test can be seen in the following example (in Python). As far as the function in_the_forest is concerned, the Person object is a duck:

Certain usually statically typed languages such as Boo and the version 4 release of C# have extra type annotations that instruct the compiler to arrange for type checking of classes to occur at run-time rather than compile time, and include run-time type checking code in the compiled output.


...
Wikipedia

...