User:Ushkin N/Comparison of programming languages/Types/Duck typing

See Duck typing.

In C#
As of C# 4.0 the compiler and runtime collaborate to implement dynamic member lookup.

In the following C# 6.0 code, the parameter duck of the method Program.InTheForest is declared as dynamic.

In CFML
The web application scripting language CFML allows function arguments to be specified as having type any. For this sort of argument, an arbitrary object can be passed in and method calls are bound dynamically at runtime. If an object does not implement a called method, a runtime exception is thrown that can be caught and handled gracefully. In ColdFusion 8, this can be picked up as a defined event onMissingMethod rather than through an exception handler. An alternative argument type of WEB-INF.cftags.component restricts the passed argument to be a ColdFusion Component (CFC), which provides better error messages should a non-object be passed in.

Other CFML application servers such as Lucee work analogously to ColdFusion's CFML implementation.

In Cobra
In addition to static typing, Cobra allows one to declare objects of type 'dynamic' and send any message to them. At run-time the message passing will either succeed or throw an exception. The 'dynamic' type is the default for object variables and method arguments when a type has not been explicitly declared for them. This feature was inspired by Objective-C.

In Common Lisp
Common Lisp includes an object-oriented system (Common Lisp Object System, or shorter CLOS) providing classes with multiple inheritance and generic functions that can specialize on multiple arguments. The combination of CLOS and Lisp's dynamic typing make duck typing a common programming style in Common Lisp.

With Common Lisp one also does not need to query the types, since at runtime an error will be signaled when a generic function is not applicable. The error can be handled with the condition system of Common Lisp. Methods are defined outside of classes and can also be defined for specific objects.

The usual development style of Common Lisp (by using a Lisp REPL like SLIME) allows also the interactive repair:

? (defclass cat ) ? (quack (make-instance 'cat)) > Error: There is no applicable method for the generic function: >     # >   when called with arguments: >     (#) > If continued: Try calling it again 1 > (defmethod quack ((a-cat cat))                (print "The cat imitates a duck.")) 1 > (continue) "The cat imitates a duck."
 * 1) 
 * 1) 

This way software can be developed by extending partially working duck typed code.

In Go
In Go, any type that has the methods required for an interface can act as that interface, regardless of whether or not it was explicitly defined or intended. Because of this, multiple sources use the term duck typing when describing Go interfaces. However, Go typically checks for compatibility at compile-time, which is why the Go designers describe the interfaces as a form of structural typing.

Although in general duck typing can be implemented with reflection, the support for reflection in Go is limited. Calling methods through reflection requires the use of interface type assertions. The runtime validates that the underlying type of a value supports all methods defined in the given interface. In duck typing, the runtime validates each method invokation separately.

In Groovy
In Groovy, the Java-derived scripting language, the below Java example can be greatly simplified, because Groovy uses duck typing by default when calling a method.

In Java
In Java duck typing may be achieved with reflection.

Running the DuckTyping class will produce the following output:

I'm a Duck, I can walk... I'm a Duck, I can swim... I'm a Duck, I can quack... I'm a Person, I can walk... I'm a Person, I can swim... Method not found: Person.quack

In Julia
Julia uses multiple dispatch, generic functions, optional type annotations and automatic type inference by default, the type  is the super-type of the whole hierarchy.

In Lua
Lua supports duck typing as part of the Metatable weak-typing system. Any reference to a table's member function is checked dynamically at run-time. If an object does not implement the requested function, a run-time error is produced. If a data member is requested, but does not exist, a nil value is returned.

In Objective-C
Objective-C, a cross between C and Smalltalk, allows one to declare objects of type 'id' and send any message to them (provided the method is declared somewhere), like in Smalltalk. The sender can test an object to see if it responds to a message, the object can decide at the time of the message whether it will respond to it or not, and, if the sender sends a message a recipient cannot respond to, an exception is raised. Thus, duck typing is fully supported by Objective-C.

Output:

Quaaaack! The person imitates a duck.

In Perl
Perl looks for method definitions in package set with  function.

Output:

Quaaaaaack! The duck has white and gray feathers. The person imitates a duck. The person takes a feather from the ground and shows it.

In PHP
PHP leans towards the Java convention of using inheritance and the user land type system (type hinting method arguments or using instanceof class or interface) in favour of duck typing. Below is an example of duck typing:

Output:

Quack Flap, Flap I try to imitate a duck quack I take an airplane

In PowerShell
This is the concept example from the beginning of the page.

In Python
Duck typing is heavily used in Python, with the canonical example being file-like classes (for example, allows a Python string to be treated as a file).

Output:

Quack, quack! Flap, Flap! I'm Quackin'! I'm Flyin'!

According to the EAFP principle, instead of checking to see if some purportedly Duck-like object has a quack method (using ), it's usually preferable to wrap the attempted quack with proper exception handling:

Or, a more common use of the principle is to just let the exception "bubble up", that is, to let the exception be raised, and let whatever function or method called the code in question deal with it (or, if nothing deals with it, to let the exception be raised to the user). This gives better feedback on bad input, and avoids masking bugs.

In Ruby
Output: Quaaaaaack! The duck has white and gray feathers. The person imitates a duck. The person takes a feather from the ground and shows it.

In Smalltalk
Duck typing is fundamental to Smalltalk. Variables have no data type, and can hold any object. Behavior is triggered by messages sent between objects. Any arbitrary string can be sent to any object as a message. The receiving object checks its method list for a matching behavior. This is the only approximation of type-checking in the language.

Moreover, a message with no matching method is not necessarily an error. In this case, the receiving object triggers its own doesNotUnderstand: method, inherited from Object. The default implementation raises an error, but this can be overridden to perform arbitrary operations based on the original message.

In Typescript
Typescript is unusual, in that it is a statically-typed language which uses duck-typing pervasively at compile time. Compile-time type checking is always based on type signatures, never inheritance. Run time type checking is done using the "instanceof" operator, which is not duck-typed.

This is similar to Go's "structural typing", but it applies to both classes and interfaces. Unlike Go, Typescript has an "implements" keyword to declare that a type should implement a particular interface. It is not required -- if a class implements all the members of interface IFoo, it can be used as an IFoo. An explicit "implements" keyword provides compile-time errors if a developer fails to correctly implement an interface which he or she had intended to.

In the following example, it is legal to assign a Seagull object to a Duck variable, even though neither class inherits from the other. Because Seagull implements both talk and swim methods, it can be used as a Duck. A Parrot object cannot be assigned to a Duck variable because it does not implement any swim method. A Fish object cannot be assigned to a Duck variable even though it has both talk and swim methods, because the talk method has the wrong signature (returning a void rather than a string).