If I have an object, how can I determine its type? (Is there an OCaml equivalent to Java's instanceof
operator?)
views:
514answers:
4There's a discussion of "Matching Objects With Patterns" on Lambda the Ultimate (the paper uses Scala as the language, so won't answer your question). A more relevant Ocaml mailing list thread indicates that there's no RTTI/safe-downcasting for objects.
For algebraic (non object) types you obviously have:
match expr with
Type1 x -> x
Type2 (x,y) -> y
called (pattern) matching
Someone did write an extension that allows down/up-casting Ocaml objects.
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
In short, you have to encode your own RTTI mechanism. OCaml provides no RTTI or up/down casting (the latter in part because inheritance and subtyping are orthogonal in OCaml rather than unified as in Java).
You could do something with strings or polymorphic variants to encode type information in your classes and objects. I believe that LablGTK does some of this, and provides a utility library to support object tagging and up/down casting.
Somewhat out-of-topic, but the OPA language (which draws heavily from some aspects of OCaml), allows the equivalent of pattern-matching on objects. So it's quite feasible.