OCaml Objects and Classes
The "O" in OCaml stands for objects. OCaml has a complete object system with classes, inheritance and late binding. In practice, most OCaml code uses modules, records and variants instead, but objects are useful when you need open-ended extension through inheritance or structural "duck typing".
Immediate objects
You can create an object directly with object ... end, without a class. val declares fields (instance variables) and method declares methods. Methods are called with #:
let counter =
object
val mutable count = 0
method increment = count <- count + 1
method value = count
end
let () =
counter#increment;
counter#increment;
Printf.printf "count = %d\n" counter#valuecount = 2
Fields are private to the object: from outside, only methods are visible.
Structural typing
An object's type lists its methods, for example < value : int; increment : unit >. Any object with the right methods fits, regardless of how it was created. This is structural typing ("duck typing", checked at compile time):
let describe obj = Printf.printf "%s: %.1f\n" obj#name obj#area
let square side = object
method name = "square"
method area = side *. side
end
let circle r = object
method name = "circle"
method area = Float.pi *. r *. r
method radius = r (* an extra method is fine *)
end
let () =
describe (square 3.0);
describe (circle 1.0)square: 9.0
circle: 3.1
The inferred type of describe is < area : float; name : string; .. > -> unit. The .. means "and possibly other methods", so circle with its extra radius method is accepted.
Classes
A class is a template for creating objects, with constructor parameters. Create instances with new:
class account (owner : string) (initial : int) =
object (self)
val mutable balance = initial
method owner = owner
method balance = balance
method deposit amount = balance <- balance + amount
method withdraw amount =
if amount > balance then Error "insufficient funds"
else begin
balance <- balance - amount;
Ok ()
end
method summary = Printf.sprintf "%s has %d" self#owner self#balance
end
let () =
let acc = new account "Mira" 100 in
acc#deposit 50;
(match acc#withdraw 500 with Ok () -> () | Error e -> print_endline ("refused: " ^ e));
ignore (acc#withdraw 30);
print_endline acc#summaryrefused: insufficient funds
Mira has 120
object (self) names the current object, like this in Java, so methods can call each other with self#method.
Inheritance and overriding
inherit reuses a parent class. A subclass can override methods, and calls through self use the overriding version (late binding):
class animal (name : string) =
object (self)
method name = name
method sound = "..."
method speak = Printf.sprintf "%s says %s" self#name self#sound
end
class dog name =
object
inherit animal name
method! sound = "woof"
end
class loud_dog name =
object
inherit dog name as super
method! speak = String.uppercase_ascii super#speak ^ "!"
end
let () =
let pets : animal list = [ new animal "Generic"; (new dog "Rex" :> animal); (new loud_dog "Max" :> animal) ] in
List.iter (fun p -> print_endline p#speak) petsGeneric says ...
Rex says woof
MAX SAYS WOOF!
method!marks an override (the!makes the compiler check that a method is really being overridden).inherit dog name as superlets you call the parent's version withsuper#speak.(x :> animal)is an explicit coercion to a supertype. OCaml never upcasts implicitly, so you need it to put different classes in one list.
Virtual classes
A virtual method has no implementation; a class containing one is virtual (abstract) and cannot be instantiated:
class virtual shape =
object (self)
method virtual area : float
method describe = Printf.sprintf "area %.2f" self#area
end
class rect w h = object inherit shape method area = w *. h end
class tri b h = object inherit shape method area = 0.5 *. b *. h end
let () = List.iter (fun s -> print_endline s#describe) [ (new rect 2.0 3.0 :> shape); (new tri 4.0 5.0 :> shape) ]area 6.00
area 10.00
Objects or modules and variants?
| Need | Usual OCaml choice |
|---|---|
| A fixed set of cases you match on | variant |
| A type with operations and hidden representation | module + abstract type |
| Many implementations of an interface, chosen at run time | records of functions, first-class modules, or objects |
| Open inheritance hierarchies, GUI widgets | objects and classes |
Test yourself
How do you call method area on object s?
s.areas#areas->areaarea s
What does .. mean in the type < name : string; .. >?
- The type is infinite
- The object may have other methods too
- A syntax error
- All methods are private
How do you treat a dog object as an animal in a list of animals?
- It happens automatically
- With an explicit coercion
(d :> animal) - With
inherit - It is impossible