Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access an object field in OCaml?

Tags:

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.

like image 749
anol Avatar asked Feb 26 '15 18:02

anol


1 Answers

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

like image 127
Jeffrey Scofield Avatar answered Nov 15 '22 09:11

Jeffrey Scofield