Search code examples
objectocamlinstanceoftypechecking

OCaml: Type Checking Objects


If I have an object, how can I determine its type? (Is there an OCaml equivalent to Java's instanceof operator?)


Solution

  • OCaml has structural typing for objects rather than nominative typing as in Java. So the type of an object is basically determined (and only determined) by its methods. Objects in OCaml can be created directly, without going through something like a class.

    You can write functions which require that its argument objects have certain methods (and that those methods have certain types); for example, the following method takes an argument that is any object with a method "bar":

    let foo x = x#bar