Why my subclass(inheritance) cannot be passed to a function requiring its super class?

Hi, I am playing with the OOP part of OCaml and I tried to implement a simple command pattern (which I am aware not ideal for OCaml, but just for fun here)

I defined a class with method execute and let a frenchEvent to inherit it.

Then, I defined a function that require a parameter of type event, and it will call the execute of the event.

Since frenchEvent is a subclass of Event, I assume that the trigger function can also use frenchEvent too.

class event =
    method execute = (); 

class frenchEvent =
  inherit event
  method! execute =
    print_string "Bonjour!"

let trigger e:event =
  e#execute in
let frenchEventObj = new frenchEvent in
  trigger frenchEventObj;

However, It throws me this error message for the last line:

This expression has type frenchEvent = < execute : unit >
but an expression was expected of type < execute : event; .. >
Type unit is not compatible with type event = < execute : unit > 
Types for method execute are incompatibleocamllsp

I must misunderstand something. Where did i do wrong?

What does the last two dots in the < execute : event; .. > mean?

This question might be trivial, sorry for that :(

You need to write let trigger (e:event) =... to say that argument has type event. The stuff you wrote means that function trigger should return value of type event, and it is not what you intended.

1 Like

Thank you very much!