Duck typing
Style of dynamic typing in object-oriented programming
- 2 min read
- 2 chapters
Related on Lably
Through Computer programming, Object (computer science) and Inheritance (object-oriented programming)
In statically typed languages
In some statically typed languages such as Boo and D, class type checking can be specified to occur at runtime rather than at compile time.
C# can invoke dynamic typing which behaves similar to duck typing, through the keyword dynamic.
Sign in to keep reading
One more chapter is free with a Lably account.
Comparison with other type systems
Structural type systems
Duck typing is similar to, but distinct from, structural typing. Structural typing is a static typing system that determines type compatibility and equivalence by a type's structure, whereas duck typing is dynamic and determines type compatibility by only that part of a type's structure that is accessed during runtime.
The TypeScript, Elm and Python languages support structural typing to varying degrees.
Protocols and interfaces
Protocols and interfaces provide a way to explicitly declare that some methods, operators or behaviors must be defined. If a third-party library implements a class that cannot be modified, a client cannot use an instance of it with an interface unknown to that library even if the class satisfies the interface requirements. A common solution to this problem is the adapter pattern. In contrast, with duck typing, the object would be accepted directly without the need for an adapter.
Templates or generic types
Template (also called generic) functions or methods apply the duck test in a static typing context; this brings all of the advantages and disadvantages of static versus dynamic type checking. Duck typing can also be more flexible in that only the methods actually called at runtime must be implemented, while templates require implementations of all methods that cannot be proven unreachable at compile time.
In languages such as Java, Scala and Objective-C, reflection may be employed to inspect whether objects implement methods or add necessary methods at runtime. For example, Java's MethodHandle API can be used in this manner.

