Duck typing, must it be dynamic?

后端 未结 8 1144
花落未央
花落未央 2020-12-13 09:55

Wikipedia used to say* about duck-typing:

In computer programming with object-oriented programming languages, duck typing is a style of dynamic

8条回答
  •  情深已故
    2020-12-13 10:28

    Duck typing means If it just fits, it's OK

    This applies to both dynamically typed

    def foo obj
        obj.quak()
    end
    

    or statically typed, compiled languages

    template 
    void foo(T& obj) {
        obj.quak();
    }
    

    The point is that in both examples, there has not been any information on the type given. Just when used (either at runtime or compile-time!), the types are checked and if all requirements are fulfilled, the code works. Values don't have an explicit type at their point of declaration.

    Structural typing relies on explicitly typing your values, just as usual - The difference is just that the concrete type is not identified by inheritance but by it's structure.

    A structurally typed code (Scala-style) for the above example would be

    def foo(obj : { def quak() : Unit }) {
        obj.quak()
    }
    

    Don't confuse this with the fact that some structurally typed languages like OCaml combine this with type inference in order to prevent us from defining the types explicitly.

提交回复
热议问题