Chapter 3 Objects in OCaml

(Chapter written by Jérôme Vouillon, Didier Rémy and Jacques Garrigue)

This chapter gives an overview of the object-oriented features ofOCaml.

Note that the relationship between object, class and type in OCaml isdifferent than in mainstream object-oriented languages such as Java andC++, so you shouldn’t assume that similar keywords mean the same thing.Object-oriented features are used much less frequently in OCaml thanin those languages. OCaml has alternatives that are often more appropriate,such as modules and functors. Indeed, many OCaml programs do not use objectsat all.

3.1 Classes and objects 3.2 Immediate objects 3.3 Reference to self 3.4 Initializers 3.5 Virtual methods 3.6 Private methods 3.7 Class interfaces 3.8 Inheritance 3.9 Multiple inheritance 3.10 Parameterized classes 3.11 Polymorphic methods 3.12 Using coercions 3.13 Functional objects 3.14 Cloning objects 3.15 Recursive classes 3.16 Binary methods 3.17 Friends

3.1 Classes and objects

The class point below defines one instance variable x and two methodsget_x and move. The initial value of the instance variable is 0.The variable x is declared mutable, so the method move can changeits value.

  1. class point =
  2. object
  3. val mutable x = 0
  4. method get_x = x
  5. method move d = x <- x + d
  6. end;;
  7. class point :
  8. object val mutable x : int method get_x : int method move : int -> unit end

We now create a new point p, instance of the point class.

  1. let p = new point;;
  2. val p : point = <obj>

Note that the type of p is point. This is an abbreviationautomatically defined by the class definition above. It stands for theobject type <get_x : int; move : int -> unit>, listing the methodsof class point along with their types.

We now invoke some methods of p:

  1. p#get_x;;
  2. - : int = 0
  1. p#move 3;;
  2. - : unit = ()
  1. p#get_x;;
  2. - : int = 3

The evaluation of the body of a class only takes place at objectcreation time. Therefore, in the following example, the instancevariable x is initialized to different values for two differentobjects.

  1. let x0 = ref 0;;
  2. val x0 : int ref = {contents = 0}
  1. class point =
  2. object
  3. val mutable x = incr x0; !x0
  4. method get_x = x
  5. method move d = x <- x + d
  6. end;;
  7. class point :
  8. object val mutable x : int method get_x : int method move : int -> unit end
  1. new point#get_x;;
  2. - : int = 1
  1. new point#get_x;;
  2. - : int = 2

The class point can also be abstracted over the initial values ofthe x coordinate.

  1. class point = fun x_init ->
  2. object
  3. val mutable x = x_init
  4. method get_x = x
  5. method move d = x <- x + d
  6. end;;
  7. class point :
  8. int ->
  9. object val mutable x : int method get_x : int method move : int -> unit end

Like in function definitions, the definition above can beabbreviated as:

  1. class point x_init =
  2. object
  3. val mutable x = x_init
  4. method get_x = x
  5. method move d = x <- x + d
  6. end;;
  7. class point :
  8. int ->
  9. object val mutable x : int method get_x : int method move : int -> unit end

An instance of the class point is now a function that expects aninitial parameter to create a point object:

  1. new point;;
  2. - : int -> point = <fun>
  1. let p = new point 7;;
  2. val p : point = <obj>

The parameter x_init is, of course, visible in the whole body of thedefinition, including methods. For instance, the method get_offsetin the class below returns the position of the object relative to itsinitial position.

  1. class point x_init =
  2. object
  3. val mutable x = x_init
  4. method get_x = x
  5. method get_offset = x - x_init
  6. method move d = x <- x + d
  7. end;;
  8. class point :
  9. int ->
  10. object
  11. val mutable x : int
  12. method get_offset : int
  13. method get_x : int
  14. method move : int -> unit
  15. end

Expressions can be evaluated and bound before defining the object bodyof the class. This is useful to enforce invariants. For instance,points can be automatically adjusted to the nearest point on a grid,as follows:

  1. class adjusted_point x_init =
  2. let origin = (x_init / 10) * 10 in
  3. object
  4. val mutable x = origin
  5. method get_x = x
  6. method get_offset = x - origin
  7. method move d = x <- x + d
  8. end;;
  9. class adjusted_point :
  10. int ->
  11. object
  12. val mutable x : int
  13. method get_offset : int
  14. method get_x : int
  15. method move : int -> unit
  16. end

(One could also raise an exception if the x_init coordinate is noton the grid.) In fact, the same effect could here be obtained bycalling the definition of class point with the value of theorigin.

  1. class adjusted_point x_init = point ((x_init / 10) * 10);;
  2. class adjusted_point : int -> point

An alternate solution would have been to define the adjustment ina special allocation function:

  1. let new_adjusted_point x_init = new point ((x_init / 10) * 10);;
  2. val new_adjusted_point : int -> point = <fun>

However, the former pattern is generally more appropriate, sincethe code for adjustment is part of the definition of the class and will beinherited.

This ability provides class constructors as can be found in otherlanguages. Several constructors can be defined this way to build objects ofthe same class but with different initialization patterns; analternative is to use initializers, as described below in section3.4.

3.2 Immediate objects

There is another, more direct way to create an object: create itwithout going through a class.

The syntax is exactly the same as for class expressions, but theresult is a single object rather than a class. All the constructsdescribed in the rest of this section also apply to immediate objects.

  1. let p =
  2. object
  3. val mutable x = 0
  4. method get_x = x
  5. method move d = x <- x + d
  6. end;;
  7. val p : < get_x : int; move : int -> unit > = <obj>
  1. p#get_x;;
  2. - : int = 0
  1. p#move 3;;
  2. - : unit = ()
  1. p#get_x;;
  2. - : int = 3

Unlike classes, which cannot be defined inside an expression,immediate objects can appear anywhere, using variables from theirenvironment.

  1. let minmax x y =
  2. if x < y then object method min = x method max = y end
  3. else object method min = y method max = x end;;
  4. val minmax : 'a -> 'a -> < max : 'a; min : 'a > = <fun>

Immediate objects have two weaknesses compared to classes: their typesare not abbreviated, and you cannot inherit from them. But these twoweaknesses can be advantages in some situations, as we will seein sections 3.3 and 3.10.

3.3 Reference to self

A method or an initializer can invoke methods on self (that is,the current object). For that, self must be explicitly bound, here tothe variable s (s could be any identifier, even though we willoften choose the name self.)

  1. class printable_point x_init =
  2. object (s)
  3. val mutable x = x_init
  4. method get_x = x
  5. method move d = x <- x + d
  6. method print = print_int s#get_x
  7. end;;
  8. class printable_point :
  9. int ->
  10. object
  11. val mutable x : int
  12. method get_x : int
  13. method move : int -> unit
  14. method print : unit
  15. end
  1. let p = new printable_point 7;;
  2. val p : printable_point = <obj>
  1. p#print;;
  2. 7- : unit = ()

Dynamically, the variable s is bound at the invocation of a method. Inparticular, when the class printable_point is inherited, the variables will be correctly bound to the object of the subclass.

A common problem with self is that, as its type may be extended insubclasses, you cannot fix it in advance. Here is a simple example.

  1. let ints = ref [];;
  2. val ints : '_weak1 list ref = {contents = []}
  1. class my_int =
  2. object (self)
  3. method n = 1
  4. method register = ints := self :: !ints
  5. end ;;
  6. Error: This expression has type < n : int; register : 'a; .. >
  7. but an expression was expected of type 'weak1
  8. Self type cannot escape its class

You can ignore the first two lines of the error message. What mattersis the last one: putting self into an external reference would make itimpossible to extend it through inheritance.We will see in section 3.12 a workaround to thisproblem.Note however that, since immediate objects are not extensible, theproblem does not occur with them.

  1. let my_int =
  2. object (self)
  3. method n = 1
  4. method register = ints := self :: !ints
  5. end;;
  6. val my_int : < n : int; register : unit > = <obj>

3.4 Initializers

Let-bindings within class definitions are evaluated before the objectis constructed. It is also possible to evaluate an expressionimmediately after the object has been built. Such code is written asan anonymous hidden method called an initializer. Therefore, it canaccess self and the instance variables.

  1. class printable_point x_init =
  2. let origin = (x_init / 10) * 10 in
  3. object (self)
  4. val mutable x = origin
  5. method get_x = x
  6. method move d = x <- x + d
  7. method print = print_int self#get_x
  8. initializer print_string "new point at "; self#print; print_newline ()
  9. end;;
  10. class printable_point :
  11. int ->
  12. object
  13. val mutable x : int
  14. method get_x : int
  15. method move : int -> unit
  16. method print : unit
  17. end
  1. let p = new printable_point 17;;
  2. new point at 10
  3. val p : printable_point = <obj>

Initializers cannot be overridden. On the contrary, all initializers areevaluated sequentially.Initializers are particularly useful to enforce invariants.Another example can be seen in section 6.1.

3.5 Virtual methods

It is possible to declare a method without actually defining it, usingthe keyword virtual. This method will be provided later insubclasses. A class containing virtual methods must be flaggedvirtual, and cannot be instantiated (that is, no object of this classcan be created). It still defines type abbreviations (treating virtual methodsas other methods.)

  1. class virtual abstract_point x_init =
  2. object (self)
  3. method virtual get_x : int
  4. method get_offset = self#get_x - x_init
  5. method virtual move : int -> unit
  6. end;;
  7. class virtual abstract_point :
  8. int ->
  9. object
  10. method get_offset : int
  11. method virtual get_x : int
  12. method virtual move : int -> unit
  13. end
  1. class point x_init =
  2. object
  3. inherit abstract_point x_init
  4. val mutable x = x_init
  5. method get_x = x
  6. method move d = x <- x + d
  7. end;;
  8. class point :
  9. int ->
  10. object
  11. val mutable x : int
  12. method get_offset : int
  13. method get_x : int
  14. method move : int -> unit
  15. end

Instance variables can also be declared as virtual, with the same effectas with methods.

  1. class virtual abstract_point2 =
  2. object
  3. val mutable virtual x : int
  4. method move d = x <- x + d
  5. end;;
  6. class virtual abstract_point2 :
  7. object val mutable virtual x : int method move : int -> unit end
  1. class point2 x_init =
  2. object
  3. inherit abstract_point2
  4. val mutable x = x_init
  5. method get_offset = x - x_init
  6. end;;
  7. class point2 :
  8. int ->
  9. object
  10. val mutable x : int
  11. method get_offset : int
  12. method move : int -> unit
  13. end

3.6 Private methods

Private methods are methods that do not appear in object interfaces.They can only be invoked from other methods of the same object.

  1. class restricted_point x_init =
  2. object (self)
  3. val mutable x = x_init
  4. method get_x = x
  5. method private move d = x <- x + d
  6. method bump = self#move 1
  7. end;;
  8. class restricted_point :
  9. int ->
  10. object
  11. val mutable x : int
  12. method bump : unit
  13. method get_x : int
  14. method private move : int -> unit
  15. end
  1. let p = new restricted_point 0;;
  2. val p : restricted_point = <obj>
  1. p#move 10 ;;
  2. Error: This expression has type restricted_point
  3. It has no method move
  1. p#bump;;
  2. - : unit = ()

Note that this is not the same thing as private and protected methodsin Java or C++, which can be called from other objects of the sameclass. This is a direct consequence of the independence between typesand classes in OCaml: two unrelated classes may produceobjects of the same type, and there is no way at the type level toensure that an object comes from a specific class. However a possibleencoding of friend methods is given in section 3.17.

Private methods are inherited (they are by default visible in subclasses),unless they are hidden by signature matching, as described below.

Private methods can be made public in a subclass.

  1. class point_again x =
  2. object (self)
  3. inherit restricted_point x
  4. method virtual move : _
  5. end;;
  6. class point_again :
  7. int ->
  8. object
  9. val mutable x : int
  10. method bump : unit
  11. method get_x : int
  12. method move : int -> unit
  13. end

The annotation virtual here is only used to mention a method withoutproviding its definition. Since we didn’t add the privateannotation, this makes the method public, keeping the originaldefinition.

An alternative definition is

  1. class point_again x =
  2. object (self : < move : _; ..> )
  3. inherit restricted_point x
  4. end;;
  5. class point_again :
  6. int ->
  7. object
  8. val mutable x : int
  9. method bump : unit
  10. method get_x : int
  11. method move : int -> unit
  12. end

The constraint on self’s type is requiring a public move method, andthis is sufficient to override private.

One could think that a private method should remain private in a subclass.However, since the method is visible in a subclass, it is always possibleto pick its code and define a method of the same name that runs thatcode, so yet another (heavier) solution would be:

  1. class point_again x =
  2. object
  3. inherit restricted_point x as super
  4. method move = super#move
  5. end;;
  6. class point_again :
  7. int ->
  8. object
  9. val mutable x : int
  10. method bump : unit
  11. method get_x : int
  12. method move : int -> unit
  13. end

Of course, private methods can also be virtual. Then, the keywords mustappear in this order method private virtual.

3.7 Class interfaces

Class interfaces are inferred from class definitions. They may alsobe defined directly and used to restrict the type of a class. Like classdeclarations, they also define a new type abbreviation.

  1. class type restricted_point_type =
  2. object
  3. method get_x : int
  4. method bump : unit
  5. end;;
  6. class type restricted_point_type =
  7. object method bump : unit method get_x : int end
  1. fun (x : restricted_point_type) -> x;;
  2. - : restricted_point_type -> restricted_point_type = <fun>

In addition to program documentation, class interfaces can be used toconstrain the type of a class. Both concrete instance variables and concreteprivate methods can be hidden by a class type constraint. Publicmethods and virtual members, however, cannot.

  1. class restricted_point' x = (restricted_point x : restricted_point_type);;
  2. class restricted_point' : int -> restricted_point_type

Or, equivalently:

  1. class restricted_point' = (restricted_point : int -> restricted_point_type);;
  2. class restricted_point' : int -> restricted_point_type

The interface of a class can also be specified in a modulesignature, and used to restrict the inferred signature of a module.

  1. module type POINT = sig
  2. class restricted_point' : int ->
  3. object
  4. method get_x : int
  5. method bump : unit
  6. end
  7. end;;
  8. module type POINT =
  9. sig
  10. class restricted_point' :
  11. int -> object method bump : unit method get_x : int end
  12. end
  1. module Point : POINT = struct
  2. class restricted_point' = restricted_point
  3. end;;
  4. module Point : POINT

3.8 Inheritance

We illustrate inheritance by defining a class of colored points thatinherits from the class of points. This class has all instancevariables and all methods of class point, plus a new instancevariable c and a new method color.

  1. class colored_point x (c : string) =
  2. object
  3. inherit point x
  4. val c = c
  5. method color = c
  6. end;;
  7. class colored_point :
  8. int ->
  9. string ->
  10. object
  11. val c : string
  12. val mutable x : int
  13. method color : string
  14. method get_offset : int
  15. method get_x : int
  16. method move : int -> unit
  17. end
  1. let p' = new colored_point 5 "red";;
  2. val p' : colored_point = <obj>
  1. p'#get_x, p'#color;;
  2. - : int * string = (5, "red")

A point and a colored point have incompatible types, since a point hasno method color. However, the function get_x below is a genericfunction applying method get_x to any object p that has thismethod (and possibly some others, which are represented by an ellipsisin the type). Thus, it applies to both points and colored points.

  1. let get_succ_x p = p#get_x + 1;;
  2. val get_succ_x : < get_x : int; .. > -> int = <fun>
  1. get_succ_x p + get_succ_x p';;
  2. - : int = 8

Methods need not be declared previously, as shown by the example:

  1. let set_x p = p#set_x;;
  2. val set_x : < set_x : 'a; .. > -> 'a = <fun>
  1. let incr p = set_x p (get_succ_x p);;
  2. val incr : < get_x : int; set_x : int -> 'a; .. > -> 'a = <fun>

3.9 Multiple inheritance

Multiple inheritance is allowed. Only the last definition of a methodis kept: the redefinition in a subclass of a method that was visible inthe parent class overrides the definition in the parent class.Previous definitions of a method can be reused by binding the relatedancestor. Below, super is bound to the ancestor printable_point.The name super is a pseudo value identifier that can only be used toinvoke a super-class method, as in super#print.

  1. class printable_colored_point y c =
  2. object (self)
  3. val c = c
  4. method color = c
  5. inherit printable_point y as super
  6. method! print =
  7. print_string "(";
  8. super#print;
  9. print_string ", ";
  10. print_string (self#color);
  11. print_string ")"
  12. end;;
  13. class printable_colored_point :
  14. int ->
  15. string ->
  16. object
  17. val c : string
  18. val mutable x : int
  19. method color : string
  20. method get_x : int
  21. method move : int -> unit
  22. method print : unit
  23. end
  1. let p' = new printable_colored_point 17 "red";;
  2. new point at (10, red)
  3. val p' : printable_colored_point = <obj>
  1. p'#print;;
  2. (10, red)- : unit = ()

A private method that has been hidden in the parent class is no longervisible, and is thus not overridden. Since initializers are treated asprivate methods, all initializers along the class hierarchy are evaluated,in the order they are introduced.

Note that for clarity’s sake, the method print is explicitly marked asoverriding another definition by annotating the method keyword withan exclamation mark !. If the method print were not overriding theprint method of printable_point, the compiler would raise an error:

  1. object
  2. method! m = ()
  3. end;;
  4. Error: The method `m' has no previous definition

This explicit overriding annotation also worksfor val and inherit:

  1. class another_printable_colored_point y c c' =
  2. object (self)
  3. inherit printable_point y
  4. inherit! printable_colored_point y c
  5. val! c = c'
  6. end;;
  7. class another_printable_colored_point :
  8. int ->
  9. string ->
  10. string ->
  11. object
  12. val c : string
  13. val mutable x : int
  14. method color : string
  15. method get_x : int
  16. method move : int -> unit
  17. method print : unit
  18. end

3.10 Parameterized classes

Reference cells can be implemented as objects.The naive definition fails to typecheck:

  1. class oref x_init =
  2. object
  3. val mutable x = x_init
  4. method get = x
  5. method set y = x <- y
  6. end;;
  7. Error: Some type variables are unbound in this type:
  8. class oref :
  9. 'a ->
  10. object
  11. val mutable x : 'a
  12. method get : 'a
  13. method set : 'a -> unit
  14. end
  15. The method get has type 'a where 'a is unbound

The reason is that at least one of the methods has a polymorphic type(here, the type of the value stored in the reference cell), thuseither the class should be parametric, or the method type should beconstrained to a monomorphic type. A monomorphic instance of the class couldbe defined by:

  1. class oref (x_init:int) =
  2. object
  3. val mutable x = x_init
  4. method get = x
  5. method set y = x <- y
  6. end;;
  7. class oref :
  8. int ->
  9. object val mutable x : int method get : int method set : int -> unit end

Note that since immediate objects do not define a class type, they haveno such restriction.

  1. let new_oref x_init =
  2. object
  3. val mutable x = x_init
  4. method get = x
  5. method set y = x <- y
  6. end;;
  7. val new_oref : 'a -> < get : 'a; set : 'a -> unit > = <fun>

On the other hand, a class for polymorphic references must explicitlylist the type parameters in its declaration. Class type parameters arelisted between [ and ]. The type parameters must also bebound somewhere in the class body by a type constraint.

  1. class ['a] oref x_init =
  2. object
  3. val mutable x = (x_init : 'a)
  4. method get = x
  5. method set y = x <- y
  6. end;;
  7. class ['a] oref :
  8. 'a -> object val mutable x : 'a method get : 'a method set : 'a -> unit end
  1. let r = new oref 1 in r#set 2; (r#get);;
  2. - : int = 2

The type parameter in the declaration may actually be constrained in thebody of the class definition. In the class type, the actual value ofthe type parameter is displayed in the constraint clause.

  1. class ['a] oref_succ (x_init:'a) =
  2. object
  3. val mutable x = x_init + 1
  4. method get = x
  5. method set y = x <- y
  6. end;;
  7. class ['a] oref_succ :
  8. 'a ->
  9. object
  10. constraint 'a = int
  11. val mutable x : int
  12. method get : int
  13. method set : int -> unit
  14. end

Let us consider a more complex example: define a circle, whose centermay be any kind of point. We put an additional typeconstraint in method move, since no free variables must remainunaccounted for by the class type parameters.

  1. class ['a] circle (c : 'a) =
  2. object
  3. val mutable center = c
  4. method center = center
  5. method set_center c = center <- c
  6. method move = (center#move : int -> unit)
  7. end;;
  8. class ['a] circle :
  9. 'a ->
  10. object
  11. constraint 'a = < move : int -> unit; .. >
  12. val mutable center : 'a
  13. method center : 'a
  14. method move : int -> unit
  15. method set_center : 'a -> unit
  16. end

An alternate definition of circle, using a constraint clause inthe class definition, is shown below. The type #point used below inthe constraint clause is an abbreviation produced by the definitionof class point. This abbreviation unifies with the type of anyobject belonging to a subclass of class point. It actually expands to< get_x : int; move : int -> unit; .. >. This leads to the followingalternate definition of circle, which has slightly strongerconstraints on its argument, as we now expect center to have amethod get_x.

  1. class ['a] circle (c : 'a) =
  2. object
  3. constraint 'a = #point
  4. val mutable center = c
  5. method center = center
  6. method set_center c = center <- c
  7. method move = center#move
  8. end;;
  9. class ['a] circle :
  10. 'a ->
  11. object
  12. constraint 'a = #point
  13. val mutable center : 'a
  14. method center : 'a
  15. method move : int -> unit
  16. method set_center : 'a -> unit
  17. end

The class colored_circle is a specialized version of classcircle that requires the type of the center to unify with#colored_point, and adds a method color. Note that when specializing aparameterized class, the instance of type parameter must always beexplicitly given. It is again written between [ and ].

  1. class ['a] colored_circle c =
  2. object
  3. constraint 'a = #colored_point
  4. inherit ['a] circle c
  5. method color = center#color
  6. end;;
  7. class ['a] colored_circle :
  8. 'a ->
  9. object
  10. constraint 'a = #colored_point
  11. val mutable center : 'a
  12. method center : 'a
  13. method color : string
  14. method move : int -> unit
  15. method set_center : 'a -> unit
  16. end

3.11 Polymorphic methods

While parameterized classes may be polymorphic in their contents, theyare not enough to allow polymorphism of method use.

A classical example is defining an iterator.

  1. List.fold_left;;
  2. - : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a = <fun>
  1. class ['a] intlist (l : int list) =
  2. object
  3. method empty = (l = [])
  4. method fold f (accu : 'a) = List.fold_left f accu l
  5. end;;
  6. class ['a] intlist :
  7. int list ->
  8. object method empty : bool method fold : ('a -> int -> 'a) -> 'a -> 'a end

At first look, we seem to have a polymorphic iterator, however thisdoes not work in practice.

  1. let l = new intlist [1; 2; 3];;
  2. val l : '_weak2 intlist = <obj>
  1. l#fold (fun x y -> x+y) 0;;
  2. - : int = 6
  1. l;;
  2. - : int intlist = <obj>
  1. l#fold (fun s x -> s ^ Int.to_string x ^ " ") "" ;;
  2. Error: This expression has type int but an expression was expected of type
  3. string

Our iterator works, as shows its first use for summation. However,since objects themselves are not polymorphic (only their constructorsare), using the fold method fixes its type for this individual object.Our next attempt to use it as a string iterator fails.

The problem here is that quantification was wrongly located: it isnot the class we want to be polymorphic, but the fold method.This can be achieved by giving an explicitly polymorphic type in themethod definition.

  1. class intlist (l : int list) =
  2. object
  3. method empty = (l = [])
  4. method fold : 'a. ('a -> int -> 'a) -> 'a -> 'a =
  5. fun f accu -> List.fold_left f accu l
  6. end;;
  7. class intlist :
  8. int list ->
  9. object method empty : bool method fold : ('a -> int -> 'a) -> 'a -> 'a end
  1. let l = new intlist [1; 2; 3];;
  2. val l : intlist = <obj>
  1. l#fold (fun x y -> x+y) 0;;
  2. - : int = 6
  1. l#fold (fun s x -> s ^ Int.to_string x ^ " ") "";;
  2. - : string = "1 2 3 "

As you can see in the class type shown by the compiler, whilepolymorphic method types must be fully explicit in class definitions(appearing immediately after the method name), quantified typevariables can be left implicit in class descriptions. Why require typesto be explicit? The problem is that (int -> int -> int) -> int -> int would also be a valid type for fold, and it happens to beincompatible with the polymorphic type we gave (automaticinstantiation only works for toplevel types variables, not for innerquantifiers, where it becomes an undecidable problem.) So the compilercannot choose between those two types, and must be helped.

However, the type can be completely omitted in the class definition ifit is already known, through inheritance or type constraints on self.Here is an example of method overriding.

  1. class intlist_rev l =
  2. object
  3. inherit intlist l
  4. method! fold f accu = List.fold_left f accu (List.rev l)
  5. end;;
  6.  

The following idiom separates description and definition.

  1. class type ['a] iterator =
  2. object method fold : ('b -> 'a -> 'b) -> 'b -> 'b end;;
  3.  
  1. class intlist' l =
  2. object (self : int #iterator)
  3. method empty = (l = [])
  4. method fold f accu = List.fold_left f accu l
  5. end;;
  6.  

Note here the (self : int #iterator) idiom, which ensures that thisobject implements the interface iterator.

Polymorphic methods are called in exactly the same way as normalmethods, but you should be aware of some limitations of typeinference. Namely, a polymorphic method can only be called if itstype is known at the call site. Otherwise, the method will be assumedto be monomorphic, and given an incompatible type.

  1. let sum lst = lst#fold (fun x y -> x+y) 0;;
  2. val sum : < fold : (int -> int -> int) -> int -> 'a; .. > -> 'a = <fun>
  1. sum l ;;
  2. Error: This expression has type intlist
  3. but an expression was expected of type
  4. < fold : (int -> int -> int) -> int -> 'a; .. >
  5. Types for method fold are incompatible

The workaround is easy: you should put a type constraint on theparameter.

  1. let sum (lst : _ #iterator) = lst#fold (fun x y -> x+y) 0;;
  2. val sum : int #iterator -> int = <fun>

Of course the constraint may also be an explicit method type.Only occurences of quantified variables are required.

  1. let sum lst =
  2. (lst : < fold : 'a. ('a -> _ -> 'a) -> 'a -> 'a; .. >)#fold (+) 0;;
  3. val sum : < fold : 'a. ('a -> int -> 'a) -> 'a -> 'a; .. > -> int = <fun>

Another use of polymorphic methods is to allow some form of implicitsubtyping in method arguments. We have already seen in section3.8 how some functions may be polymorphic in theclass of their argument. This can be extended to methods.

  1. class type point0 = object method get_x : int end;;
  2. class type point0 = object method get_x : int end
  1. class distance_point x =
  2. object
  3. inherit point x
  4. method distance : 'a. (#point0 as 'a) -> int =
  5. fun other -> abs (other#get_x - x)
  6. end;;
  7. class distance_point :
  8. int ->
  9. object
  10. val mutable x : int
  11. method distance : #point0 -> int
  12. method get_offset : int
  13. method get_x : int
  14. method move : int -> unit
  15. end
  1. let p = new distance_point 3 in
  2. (p#distance (new point 8), p#distance (new colored_point 1 "blue"));;
  3. - : int * int = (5, 2)

Note here the special syntax (#point0 as 'a) we have to use toquantify the extensible part of #point0. As for the variable binder,it can be omitted in class specifications. If you want polymorphisminside object field it must be quantified independently.

  1. class multi_poly =
  2. object
  3. method m1 : 'a. (< n1 : 'b. 'b -> 'b; .. > as 'a) -> _ =
  4. fun o -> o#n1 true, o#n1 "hello"
  5. method m2 : 'a 'b. (< n2 : 'b -> bool; .. > as 'a) -> 'b -> _ =
  6. fun o x -> o#n2 x
  7. end;;
  8. class multi_poly :
  9. object
  10. method m1 : < n1 : 'b. 'b -> 'b; .. > -> bool * string
  11. method m2 : < n2 : 'b -> bool; .. > -> 'b -> bool
  12. end

In method m1, o must be an object with at least a method n1,itself polymorphic. In method m2, the argument of n2 and x musthave the same type, which is quantified at the same level as 'a.

3.12 Using coercions

Subtyping is never implicit. There are, however, two ways to performsubtyping. The most general construction is fully explicit: both thedomain and the codomain of the type coercion must be given.

We have seen that points and colored points have incompatible types.For instance, they cannot be mixed in the same list. However, acolored point can be coerced to a point, hiding its color method:

  1. let colored_point_to_point cp = (cp : colored_point :> point);;
  2. val colored_point_to_point : colored_point -> point = <fun>
  1. let p = new point 3 and q = new colored_point 4 "blue";;
  2. val p : point = <obj>
  3. val q : colored_point = <obj>
  1. let l = [p; (colored_point_to_point q)];;
  2. val l : point list = [<obj>; <obj>]

An object of type t can be seen as an object of type t'only if t is a subtype of t'. For instance, a point cannot beseen as a colored point.

  1. (p : point :> colored_point);;
  2. Error: Type point = < get_offset : int; get_x : int; move : int -> unit >
  3. is not a subtype of
  4. colored_point =
  5. < color : string; get_offset : int; get_x : int;
  6. move : int -> unit >
  7. The first object type has no method color

Indeed, narrowing coercions without runtime checks would be unsafe.Runtime type checks might raise exceptions, and they would requirethe presence of type information at runtime, which is not the case inthe OCaml system.For these reasons, there is no such operation available in the language.

Be aware that subtyping and inheritance are not related. Inheritance is asyntactic relation between classes while subtyping is a semantic relationbetween types. For instance, the class of colored points could have beendefined directly, without inheriting from the class of points; the type ofcolored points would remain unchanged and thus still be a subtype ofpoints.

The domain of a coercion can often be omitted. For instance, one candefine:

  1. let to_point cp = (cp :> point);;
  2. val to_point : #point -> point = <fun>

In this case, the function colored_point_to_point is an instance of thefunction to_point. This is not always true, however. The fullyexplicit coercion is more precise and is sometimes unavoidable.Consider, for example, the following class:

  1. class c0 = object method m = {< >} method n = 0 end;;
  2. class c0 : object ('a) method m : 'a method n : int end

The object type c0 is an abbreviation for <m : 'a; n : int> as 'a.Consider now the type declaration:

  1. class type c1 = object method m : c1 end;;
  2. class type c1 = object method m : c1 end

The object type c1 is an abbreviation for the type <m : 'a> as 'a.The coercion from an object of type c0 to an object of type c1 iscorrect:

  1. fun (x:c0) -> (x : c0 :> c1);;
  2. - : c0 -> c1 = <fun>

However, the domain of the coercion cannot always be omitted.In that case, the solution is to use the explicit form.Sometimes, a change in the class-type definition can also solve the problem

  1. class type c2 = object ('a) method m : 'a end;;
  2. class type c2 = object ('a) method m : 'a end
  1. fun (x:c0) -> (x :> c2);;
  2. - : c0 -> c2 = <fun>

While class types c1 and c2 are different, both object typesc1 and c2 expand to the same object type (same method names and types).Yet, when the domain of a coercion is left implicit and its co-domainis an abbreviation of a known class type, then the class type, ratherthan the object type, is used to derive the coercion function. Thisallows leaving the domain implicit in most cases when coercing form asubclass to its superclass.The type of a coercion can always be seen as below:

  1. let to_c1 x = (x :> c1);;
  2. val to_c1 : < m : #c1; .. > -> c1 = <fun>
  1. let to_c2 x = (x :> c2);;
  2. val to_c2 : #c2 -> c2 = <fun>

Note the difference between these two coercions: in the case of toc2,the type#c2 = < m : 'a; .. > as 'a is polymorphically recursive (accordingto the explicit recursion in the class type of c2); hence thesuccess of applying this coercion to an object of class c0.On the other hand, in the first case, c1 was only expanded andunrolled twice to obtain < m : < m : c1; .. >; .. > (remember #c1 = < m : c1; .. >), without introducing recursion.You may also note that the type of to_c2 is #c2 -> c2 whilethe type of to_c1 is more general than #c1 -> c1. This is not always true,since there are class types for which some instances of #c are not subtypesof c, as explained in section 3.16. Yet, forparameterless classes the coercion ( :> c) is always more general than(_ : #c :> c).

A common problem may occur when one tries to define a coercion to aclass c while defining class c. The problem is due to the typeabbreviation not being completely defined yet, and so its subtypes are notclearly known. Then, a coercion ( :> c) or ( : #c :> c) is taken to bethe identity function, as in

  1. function x -> (x :> 'a);;
  2. - : 'a -> 'a = <fun>

As a consequence, if the coercion is applied to self, as in thefollowing example, the type of self is unified with the closed typec (a closed object type is an object type without ellipsis). Thiswould constrain the type of self be closed and is thus rejected.Indeed, the type of self cannot be closed: this would prevent anyfurther extension of the class. Therefore, a type error is generatedwhen the unification of this type with another type would result in aclosed object type.

  1. class c = object method m = 1 end
  2. and d = object (self)
  3. inherit c
  4. method n = 2
  5. method as_c = (self :> c)
  6. end;;
  7. Error: This expression cannot be coerced to type c = < m : int >; it has type
  8. < as_c : c; m : int; n : int; .. >
  9. but is here used with type c
  10. Self type cannot escape its class

However, the most common instance of this problem, coercing self toits current class, is detected as a special case by the type checker,and properly typed.

  1. class c = object (self) method m = (self :> c) end;;
  2. class c : object method m : c end

This allows the following idiom, keeping a list of all objectsbelonging to a class or its subclasses:

  1. let all_c = ref [];;
  2. val all_c : '_weak3 list ref = {contents = []}
  1. class c (m : int) =
  2. object (self)
  3. method m = m
  4. initializer all_c := (self :> c) :: !all_c
  5. end;;
  6. class c : int -> object method m : int end

This idiom can in turn be used to retrieve an object whose type hasbeen weakened:

  1. let rec lookup_obj obj = function [] -> raise Not_found
  2. | obj' :: l ->
  3. if (obj :> < >) = (obj' :> < >) then obj' else lookup_obj obj l ;;
  4. val lookup_obj : < .. > -> (< .. > as 'a) list -> 'a = <fun>
  1. let lookup_c obj = lookup_obj obj !all_c;;
  2. val lookup_c : < .. > -> < m : int > = <fun>

The type < m : int > we see here is just the expansion of c, dueto the use of a reference; we have succeeded in getting back an objectof type c.

The previous coercion problem can often be avoided by firstdefining the abbreviation, using a class type:

  1. class type c' = object method m : int end;;
  2. class type c' = object method m : int end
  1. class c : c' = object method m = 1 end
  2. and d = object (self)
  3. inherit c
  4. method n = 2
  5. method as_c = (self :> c')
  6. end;;
  7. class c : c'
  8. and d : object method as_c : c' method m : int method n : int end

It is also possible to use a virtual class. Inheriting from this classsimultaneously forces all methods of c to have the sametype as the methods of c'.

  1. class virtual c' = object method virtual m : int end;;
  2. class virtual c' : object method virtual m : int end
  1. class c = object (self) inherit c' method m = 1 end;;
  2. class c : object method m : int end

One could think of defining the type abbreviation directly:

  1. type c' = <m : int>;;
  2.  

However, the abbreviation #c' cannot be defined directly in a similar way.It can only be defined by a class or a class-type definition.This is because a #-abbreviation carries an implicit anonymousvariable .. that cannot be explicitly named.The closer you get to it is:

  1. type 'a c'_class = 'a constraint 'a = < m : int; .. >;;
  2.  

with an extra type variable capturing the open object type.

3.13 Functional objects

It is possible to write a version of class point without assignmentson the instance variables. The override construct {< … >} returns a copy of“self” (that is, the current object), possibly changing the value ofsome instance variables.

  1. class functional_point y =
  2. object
  3. val x = y
  4. method get_x = x
  5. method move d = {< x = x + d >}
  6. method move_to x = {< x >}
  7. end;;
  8. class functional_point :
  9. int ->
  10. object ('a)
  11. val x : int
  12. method get_x : int
  13. method move : int -> 'a
  14. method move_to : int -> 'a
  15. end
  1. let p = new functional_point 7;;
  2. val p : functional_point = <obj>
  1. p#get_x;;
  2. - : int = 7
  1. (p#move 3)#get_x;;
  2. - : int = 10
  1. (p#move_to 15)#get_x;;
  2. - : int = 15
  1. p#get_x;;
  2. - : int = 7

As with records, the form {< x >} is an elided version of{< x = x >} which avoids the repetition of the instance variable name.Note that the type abbreviation functional_point is recursive, which canbe seen in the class type of functional_point: the type of self is 'aand 'a appears inside the type of the method move.

The above definition of functional_point is not equivalentto the following:

  1. class bad_functional_point y =
  2. object
  3. val x = y
  4. method get_x = x
  5. method move d = new bad_functional_point (x+d)
  6. method move_to x = new bad_functional_point x
  7. end;;
  8. class bad_functional_point :
  9. int ->
  10. object
  11. val x : int
  12. method get_x : int
  13. method move : int -> bad_functional_point
  14. method move_to : int -> bad_functional_point
  15. end

While objects of either class will behave the same, objects of theirsubclasses will be different. In a subclass of bad_functional_point,the method move willkeep returning an object of the parent class. On the contrary, in asubclass of functional_point, the method move will return anobject of the subclass.

Functional update is often used in conjunction with binary methodsas illustrated in section 6.2.1.

3.14 Cloning objects

Objects can also be cloned, whether they are functional or imperative.The library function Oo.copy makes a shallow copy of an object. That is,it returns a new object that has the same methods and instancevariables as its argument. Theinstance variables are copied but their contents are shared.Assigning a new value to an instance variable of the copy (using a methodcall) will not affect instance variables of the original, and conversely.A deeper assignment (for example if the instance variable is a reference cell)will of course affect both the original and the copy.

The type of Oo.copy is the following:

  1. Oo.copy;;
  2. - : (< .. > as 'a) -> 'a = <fun>

The keyword as in that type binds the type variable 'a tothe object type < .. >. Therefore, Oo.copy takes an object withany methods (represented by the ellipsis), and returns an object ofthe same type. The type of Oo.copy is different from type < .. > -> < .. > as each ellipsis represents a different set of methods.Ellipsis actually behaves as a type variable.

  1. let p = new point 5;;
  2. val p : point = <obj>
  1. let q = Oo.copy p;;
  2. val q : point = <obj>
  1. q#move 7; (p#get_x, q#get_x);;
  2. - : int * int = (5, 12)

In fact, Oo.copy p will behave as p#copy assuming that a publicmethod copy with body {< >} has been defined in the class of p.

Objects can be compared using the generic comparison functions = and <>.Two objects are equal if and only if they are physically equal. Inparticular, an object and its copy are not equal.

  1. let q = Oo.copy p;;
  2. val q : point = <obj>
  1. p = q, p = p;;
  2. - : bool * bool = (false, true)

Other generic comparisons such as (<, <=, …) can also be used onobjects. Therelation < defines an unspecified but strict ordering on objects. Theordering relationship between two objects is fixed once for all after thetwo objects have been created and it is not affected by mutation of fields.

Cloning and override have a non empty intersection.They are interchangeable when used within an object and withoutoverriding any field:

  1. class copy =
  2. object
  3. method copy = {< >}
  4. end;;
  5. class copy : object ('a) method copy : 'a end
  1. class copy =
  2. object (self)
  3. method copy = Oo.copy self
  4. end;;
  5. class copy : object ('a) method copy : 'a end

Only the override can be used to actually override fields, andonly the Oo.copy primitive can be used externally.

Cloning can also be used to provide facilities for saving andrestoring the state of objects.

  1. class backup =
  2. object (self : 'mytype)
  3. val mutable copy = None
  4. method save = copy <- Some {< copy = None >}
  5. method restore = match copy with Some x -> x | None -> self
  6. end;;
  7. class backup :
  8. object ('a)
  9. val mutable copy : 'a option
  10. method restore : 'a
  11. method save : unit
  12. end

The above definition will only backup one level.The backup facility can be added to any class by using multiple inheritance.

  1. class ['a] backup_ref x = object inherit ['a] oref x inherit backup end;;
  2. class ['a] backup_ref :
  3. 'a ->
  4. object ('b)
  5. val mutable copy : 'b option
  6. val mutable x : 'a
  7. method get : 'a
  8. method restore : 'b
  9. method save : unit
  10. method set : 'a -> unit
  11. end
  1. let rec get p n = if n = 0 then p # get else get (p # restore) (n-1);;
  2. val get : (< get : 'b; restore : 'a; .. > as 'a) -> int -> 'b = <fun>
  1. let p = new backup_ref 0 in
  2. p # save; p # set 1; p # save; p # set 2;
  3. [get p 0; get p 1; get p 2; get p 3; get p 4];;
  4. - : int list = [2; 1; 1; 1; 1]

We can define a variant of backup that retains all copies. (We alsoadd a method clear to manually erase all copies.)

  1. class backup =
  2. object (self : 'mytype)
  3. val mutable copy = None
  4. method save = copy <- Some {< >}
  5. method restore = match copy with Some x -> x | None -> self
  6. method clear = copy <- None
  7. end;;
  8. class backup :
  9. object ('a)
  10. val mutable copy : 'a option
  11. method clear : unit
  12. method restore : 'a
  13. method save : unit
  14. end
  1. class ['a] backup_ref x = object inherit ['a] oref x inherit backup end;;
  2. class ['a] backup_ref :
  3. 'a ->
  4. object ('b)
  5. val mutable copy : 'b option
  6. val mutable x : 'a
  7. method clear : unit
  8. method get : 'a
  9. method restore : 'b
  10. method save : unit
  11. method set : 'a -> unit
  12. end
  1. let p = new backup_ref 0 in
  2. p # save; p # set 1; p # save; p # set 2;
  3. [get p 0; get p 1; get p 2; get p 3; get p 4];;
  4. - : int list = [2; 1; 0; 0; 0]

3.15 Recursive classes

Recursive classes can be used to define objects whose types aremutually recursive.

  1. class window =
  2. object
  3. val mutable top_widget = (None : widget option)
  4. method top_widget = top_widget
  5. end
  6. and widget (w : window) =
  7. object
  8. val window = w
  9. method window = window
  10. end;;
  11. class window :
  12. object
  13. val mutable top_widget : widget option
  14. method top_widget : widget option
  15. end
  16. and widget : window -> object val window : window method window : window end

Although their types are mutually recursive, the classes widget andwindow are themselves independent.

3.16 Binary methods

A binary method is a method which takes an argument of the same typeas self. The class comparable below is a template for classes with abinary method leq of type 'a -> bool where the type variable 'ais bound to the type of self. Therefore, #comparable expands to < leq : 'a -> bool; .. > as 'a. We see here that the binder as alsoallows writing recursive types.

  1. class virtual comparable =
  2. object (_ : 'a)
  3. method virtual leq : 'a -> bool
  4. end;;
  5. class virtual comparable : object ('a) method virtual leq : 'a -> bool end

We then define a subclass money of comparable. The class moneysimply wraps floats as comparable objects. We will extend it below withmore operations. We have to use a type constraint on the class parameter xbecause the primitive <= is a polymorphic function inOCaml. The inherit clause ensures that the type of objectsof this class is an instance of #comparable.

  1. class money (x : float) =
  2. object
  3. inherit comparable
  4. val repr = x
  5. method value = repr
  6. method leq p = repr <= p#value
  7. end;;
  8. class money :
  9. float ->
  10. object ('a)
  11. val repr : float
  12. method leq : 'a -> bool
  13. method value : float
  14. end

Note that the type money is not a subtype of typecomparable, as the self type appears in contravariant positionin the type of method leq.Indeed, an object m of class money has a method leqthat expects an argument of type money since it accessesits value method. Considering m of type comparable would allow acall to method leq on m with an argument that does not have a methodvalue, which would be an error.

Similarly, the type money2 below is not a subtype of type money.

  1. class money2 x =
  2. object
  3. inherit money x
  4. method times k = {< repr = k *. repr >}
  5. end;;
  6. class money2 :
  7. float ->
  8. object ('a)
  9. val repr : float
  10. method leq : 'a -> bool
  11. method times : float -> 'a
  12. method value : float
  13. end

It is however possible to define functions that manipulate objects oftype either money or money2: the function minwill return the minimum of any two objects whose type unifies with#comparable. The type of min is not the same as #comparable -> #comparable -> #comparable, as the abbreviation #comparable hides atype variable (an ellipsis). Each occurrence of this abbreviationgenerates a new variable.

  1. let min (x : #comparable) y =
  2. if x#leq y then x else y;;
  3. val min : (#comparable as 'a) -> 'a -> 'a = <fun>

This function can be applied to objects of type moneyor money2.

  1. (min (new money 1.3) (new money 3.1))#value;;
  2. - : float = 1.3
  1. (min (new money2 5.0) (new money2 3.14))#value;;
  2. - : float = 3.14

More examples of binary methods can be found in sections6.2.1 and 6.2.3.

Note the use of override for method times.Writing new money2 (k . repr) instead of {< repr = k . repr >}would not behave well with inheritance: in a subclass money3 of money2the times method would return an object of class money2 but not of classmoney3 as would be expected.

The class money could naturally carry another binary method. Here is adirect definition:

  1. class money x =
  2. object (self : 'a)
  3. val repr = x
  4. method value = repr
  5. method print = print_float repr
  6. method times k = {< repr = k *. x >}
  7. method leq (p : 'a) = repr <= p#value
  8. method plus (p : 'a) = {< repr = x +. p#value >}
  9. end;;
  10. class money :
  11. float ->
  12. object ('a)
  13. val repr : float
  14. method leq : 'a -> bool
  15. method plus : 'a -> 'a
  16. method print : unit
  17. method times : float -> 'a
  18. method value : float
  19. end

3.17 Friends

The above class money reveals a problem that often occurs with binarymethods. In order to interact with other objects of the same class, therepresentation of money objects must be revealed, using a method such asvalue. If we remove all binary methods (here plus and leq),the representation can easily be hidden inside objects by removing the methodvalue as well. However, this is not possible as soon as some binarymethod requires access to the representation of objects of the sameclass (other than self).

  1. class safe_money x =
  2. object (self : 'a)
  3. val repr = x
  4. method print = print_float repr
  5. method times k = {< repr = k *. x >}
  6. end;;
  7. class safe_money :
  8. float ->
  9. object ('a)
  10. val repr : float
  11. method print : unit
  12. method times : float -> 'a
  13. end

Here, the representation of the object is known only to a particular object.To make it available to other objects of the same class, we are forced tomake it available to the whole world. However we can easily restrict thevisibility of the representation using the module system.

  1. module type MONEY =
  2. sig
  3. type t
  4. class c : float ->
  5. object ('a)
  6. val repr : t
  7. method value : t
  8. method print : unit
  9. method times : float -> 'a
  10. method leq : 'a -> bool
  11. method plus : 'a -> 'a
  12. end
  13. end;;
  14.  
  1. module Euro : MONEY =
  2. struct
  3. type t = float
  4. class c x =
  5. object (self : 'a)
  6. val repr = x
  7. method value = repr
  8. method print = print_float repr
  9. method times k = {< repr = k *. x >}
  10. method leq (p : 'a) = repr <= p#value
  11. method plus (p : 'a) = {< repr = x +. p#value >}
  12. end
  13. end;;
  14.  

Another example of friend functions may be found in section6.2.3. These examples occur when a group of objects (hereobjects of the same class) and functions should see each others internalrepresentation, while their representation should be hidden from theoutside. The solution is always to define all friends in the same module,give access to the representation and use a signature constraint to make therepresentation abstract outside the module.