How to model a GUI view hierarchy using classes/objects

Here’s a simplified version of the problem I’m facing:

class view = object (_ : 'a)
    method addSubview (_v : 'a) =
        ()
end

class button = object
    inherit view
    method setTitle (_title : string) =
        ()
end

let () =
    let v = new view in
    let b = new button in
    v#addSubview (b : button :> view)

The compiler is not happy:

Error: Type
         button = < addSubview : button -> unit; setTitle : string -> unit >
       is not a subtype of view = < addSubview : view -> unit > 
       Type view = < addSubview : view -> unit > is not a subtype of
         button = < addSubview : button -> unit; setTitle : string -> unit > 

How can I express the fact that button is a subtype of view and can be added as a subview of any view?

All you need to change is:

class view = object
    method addSubview (_v : view) = ()
end
...

Yes, that works. Isn’t this an example of a “binary method” as discussed in the link below?
https://caml.inria.fr/pub/docs/manual-ocaml/objectexamples.html#sec40

Indeed. And as stated in the manual, in presence of binary methods, inheritance does not imply subtyping.

2 Likes