Can we merge 2 objects compactly?

Let’s say I have 2 objects defined with
type a = <foo: int>
type b = <bar: int>

and then
let a = object method foo = 1 end
let b = object method bar = 2 end

Is there a way I can combine a and b in an object c that have both methods?

I know I can do
let c = object
method foo = a#foo
method bar = b#bar
end

But is there a more compact way, especially if both a and b have lots of methods
and I don’t want to repeat all those methods.

The short answer is no.

You can either use classes or modules for that though:

(* Classes *)
class a = object method foo = 1 end
class b = object method bar = 2 end
class c = object inherit a inherit b end

(* Modules *)
module A = struct let foo = 1 end
module B = struct let bar = 2 end
module C = struct include A include B end

(* First-class modules *)
module type A = sig val foo : int end
module type B = sig val bar : int end
module type C = sig include A include B end
let a = (module struct let foo = 1 end : A)
let b = (module struct let bar = 2 end : B)
let c = (module struct include (val a : A) include (val b : B) end : C)
2 Likes

To expand on vlaviron’s answer, what you are trying to do is called ‘delegation’, and some languages support it, eg Golang comes to mind. I don’t know of many languages that do so.