I created a point
class in OCaml, consisting of a pair of int
s and a set
method:
# class point (x : int) (y : int) =
object
val mutable x = x
val mutable y = y
method set x' y' = x <- x'; y <- y'
end;;
class point :
int ->
int ->
object
val mutable x : int
val mutable y : int
method set : int -> int -> unit
end
Then I instantiated a point:
# let p = new point 1 2;;
val p : point = <obj>
But I cannot access its fields:
# p#x;;
Error: This expression has type point
It has no method x
# p.x;;
Error: Unbound record field x
How can I access an object's fields?
Note that the OCaml manual does mention private methods, but nowhere it mentions whether fields are private or public. And, unlike private methods, fields do appear in the class signature, as if they were public.
Fields of an object are private. You need to expose an accessor method to access them from outside.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With