7 ms·
Not like "extends" or "implements". If a class implements all the methods of the interface (as seen at compile-time - same method name, arguments, returns) the
by kubanczyk 7y ago
Not like "extends" or "implements".
If a class implements all the methods of the interface (as seen at compile-time - same method name, arguments, returns) then that's it, period. Compiler will allow you to use it. Beyond that the interface doesn't "know" about the class and the class doesn't "know" about the interface.
So it doesn't matter the interface didn't even exist when that class was written.
- hesk 7y agoSounds a lot like Python's duck typing to me. (Although Python would coerce the types if they don't match.)
- kevincox 7y agoIt is. "Structural typing" is basically "compile time duck typing". One major notable advantage is that you are checking the existence of every method you may call, not just the ones your tests happen to use.
- mcqueenjordan 7y agoSimilar in some ways, but duck typing is a misnomer because it doesn't involve typing. These are type classes, or what Rust calls Traits.
- aboodman 7y ago> duck typing is a misnomer because it doesn't involve ... dang, the joke was so close
- Too 7y agoJavascript (without typescript) also has duck typing. The difference with structural typing is that the interface is formalized and enforced compile time. Python 3.7 added compile structural typing using what they call Protocols. It works very similar to typescript. See https://www.python.org/dev/peps/pep-0544/ https://www.python.org/dev/peps/pep-0544/