OCaml: Type Checking Objects

Nick Heiner picture Nick Heiner · Sep 15, 2009 · Viewed 17.5k times · Source

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

Answer

newacct picture newacct · Sep 15, 2009

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