anol
anol

Reputation: 8953

How to access an object field in OCaml?

I created a point class in OCaml, consisting of a pair of ints 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.

Upvotes: 7

Views: 947

Answers (1)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66793

Fields of an object are private. You need to expose an accessor method to access them from outside.

Upvotes: 11

Related Questions