在 OCaml 中使用 class

Work with class in OCaml

我想在 class t 中使用我的类型 test_type 创建函数。我的代码:

type test_type = [`t1|`t2]

let get_types =
  function
   | `t1 -> "t1"
   | `t2 -> "t2";;

class type class_types =
  object
    method t_types : test_type
    method test : (string -> string -> test_type -> unit) -> unit
end;;

class t : class_types =
  object
    method test par1 ?(par2="no par2") ?(par3=`t1) () =
      print_endline("--->"^par1);
      print_endline("--->"^par2);
      print_endline("--->"^get_types par3)
end;;

let t_run = new t;;
t_run # test "parametr1" ~par3:`t2 ();;

是return错误

The class type is not matched by the class type class_types
The first class type has no method t_types

如何操作?

只是您的 t 实现缺少方法 t_types,它在 class 类型 class_types 中定义。

除此之外,方法 test 的类型是 string -> ?par2: string -> ?par3: test_type -> unit -> unit,与 class 类型不兼容。