Reputation: 797
I have this code
class person name_init =
object
val name = name_init
method get_name = name
end;;
let p1 = new person "Steven"
and p2 = new person "John" in
print_endline p1#get_name;
print_endline p2#get_name;;
It complains that get_name and val name in my person object are of unbound type, which I realize is accurate. How would I specify that name_init (and therefore name and get_name) is of type string in OCaml?
Upvotes: 2
Views: 562
Reputation: 35280
OCaml requires all values in the class
expression to be either concrete, or bound to a type parameter. As a consequence, when type system infers that the type of your expression is polymorphic you need to do something with it. You have two choices:
In the first case, the constraint can be put anywhere inside the class expression, given that this constraint will not allow the polymorphic expression to escape the class expression. A few examples, to demonstrate the idea:
Constraining at the instance variable specification:
class person name_init =
object
val name : string = name_init
method get_name = name
end
Constraining at the method specification:
class person name_init =
object
val name = name_init
method get_name : string = name
end
At your example, we have two more places where you can put the constraint, but I think that the idea is rather clear.
Upvotes: 0
Reputation: 57969
Specify parameter types for functions (including constructors) like this:
class person (name_init : string) =
…
If you have multiple parameters, put them all in the parens.
Upvotes: 1