Static Typing – How Can a Statically Typed Language Support Duck Typing?

duck-typingdynamic-typingstatic-typing

I understand what dynamic and static type systems are, and what duck typing is. But I don't understand how you can have a static language that supports duck typing. To my understanding only a dynamically typed language can support duck typing.

This answer from StackOverflow explains that "Duck typing is something that is completely orthogonal to static, dynamic, weak, or strong typing." It gives an example from C++ for duck typing in a statically typed language, but I'm not a C++ programmer and I don't understand it.

I'd like an explanation of how it's possible for a static language to support duck typing.

Best Answer

In my experience, it is simply a language that uses static typing with a Structural Type System. It essentially applies the "walks like a duck, talks like a duck" check at compile type so that the programmer doesn't need to provide annotations to specifically sub-type things.

This has a very large benefit when you're trying to glue two (or more) libraries together. With a nominative type system, if you had some interface in one library and an object in the other, they don't know about one another and can't sub-type - even if the object satisfies the interface's requirements. Structural typing makes that okay.

Making the language static just means that the compiler does that check at compile time, giving you an error early (and clearly) when that object doesn't really satisfy the interface.

There are a few esoteric languages that do this, but most structurally typed languages are also dynamically typed and almost all nominative typed languages are also statically typed.

Related Topic