Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
[Caml-list] How to downcast in OCAML
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: tim@f...
Subject: [Caml-list] How to downcast in OCAML

For what it's worth (which may not be much), it is possible to write
classes in OCAML that are downcastable.  Here's how.

Tim Freeman
GPG public key fingerprint ECDF 46F8 3B80 BB9E 575D  7180 76DF FE00 34B1 5C78 

module type Foo = sig
  class type superclass = object
    method data: exn
  class subclass_1: string -> object
    inherit superclass
    method s: string
  exception Subclass_1 of subclass_1
  class subclass_2: int -> object
    inherit superclass
    method i: int
  exception Subclass_2 of subclass_2
  val x: superclass

module Foo: Foo = struct

  class type superclass = object
    method data: exn
      (* You can put more methods here if you like. *)
  class subclass_1_impl (s: string) (makeexn: subclass_1_impl -> exn) =
  object (self: 'self)
    constraint 'self = #superclass
    method data: exn = makeexn (self :> subclass_1_impl)
    method s: string = s
  exception Subclass_1 of subclass_1_impl
  class subclass_1 (s: string) = subclass_1_impl s (fun sc -> Subclass_1 sc)
  class subclass_2_impl (i: int) (makeexn: subclass_2_impl -> exn) =
  object (self: 'self)
    constraint 'self = #superclass
    method data: exn = makeexn (self :> subclass_2_impl)
    method i: int = i
  exception Subclass_2 of subclass_2_impl
  class subclass_2 (i: int) = subclass_2_impl i (fun sc -> Subclass_2 sc)
  let _ = Random.self_init ()

  let x: superclass =
    if Random.bits () mod 2 = 0 then
      (new subclass_1 "blort" :> superclass)
      (new subclass_2 17 :> superclass)
  let _ =
    match x#data with
        Subclass_1 s1 -> Format.printf "s is %s.\n@?" s1#s
      | Subclass_2 s2 -> Format.printf "i is %d.\n@?" s2#i
      | _ -> failwith "Downcast failed"
To unsubscribe, mail Archives:
Bug reports: FAQ:
Beginner's list: