Trying to understand an object error


#1

Take the following code.

let newTruck = {
    val drive = 4;
    pub buildTruck = (~make, ~model) => {j|You built a new $make $model with $drive-wheel drive.|j};
};
let toyotaTundra = newTruck#buildTruck(~make="Toyota", ~model="Tundra");

This will throw a warning that drive is unused, but the object transpiles to JavaScript correctly. Why?


#2

I’m getting this warning:

Warning number 27
OCaml preview 2:10-15

unused variable this.

If I add the following immediately after the opening brace, the warning goes away:

as _this;

The warning was coming from the fact that OCaml objects implicitly have a ‘this’ value in scope that represent the object itself. If it’s not used, it the compiler warns you. You can turn off the warning just like for any unused name by explicitly prefixing it with an underscore.

Overall, I would advise avoiding OOP in OCaml, this will make headaches like this go away :slight_smile:


#3

That was exactly it. Thanks.


#4

But wouldn’t it reduce it to mere Caml? :smiley:


#5

I would still consider it OCaml, objects as structurally-typed simple data containers are still super useful, it’s just OOP that gives headaches :slight_smile:


#6

Precisely this. Think of records as positionally-typed named tuples, and objects as row-typed named tuples (though closer to records of function pointers internally). They have different performance characteristics, different purposes, etc…