tags:

views:

167

answers:

2

I'm trying to get a grip on the OCaml language syntax and am having some trouble with applying some OOP structures. My goal with the below code is to have a class bar that inherits from a virtual class foo. The virtual class contains three virtual methods that I hope to take an instance of a "player" object as a parameter. When I compile the below code, I get the error: The method doThis has type 'a -> 'b but is expected to have type player . What does this mean (remember, I'm new at this) and how do I go about correcting it?

Thanks!

class player =
object

end;;

class virtual foo =
object (self)
 method virtual doThis : player
 method virtual doThat : player
 method virtual notifyAll : player array
end;;

class bar (playersIn: player array) =
object (self)
 inherit foo
 method doThis (p:player) = Printf.printf "%s\n" "This!"
 method doThat (p:player) = Printf.printf "%s\n" "That!"
 method notifyAll (p:player array) = Printf.printf "%s\n" "Notifying!"
end;;
+2  A: 

(I don't know OCaml, but I do know F#, and they are similar, so hopefully I am guessing right.)

Try changing

method virtual doThis : player 
method virtual doThat : player 
method virtual notifyAll : player array

to

method virtual doThis : player -> unit
method virtual doThat : player -> unit
method virtual notifyAll : player array -> unit
Brian
That did the trick. Thanks!
Mat
In that case, it sounds like you originally defined these to be just 'values' or 'properties', the -> unit makes it have a function type (takes player as a parameter and return no result).
Brian
A: 

I believe the previous answer to this is correct: the methods in question need their types to be functions that return unit.

Another, more general piece of advice: don't start learning OCaml by starting to learn the object system. Objects in OCaml can be useful, but the cases where you really want to be programming with objects are few and far between. And you won't be able to understand OCaml's object system until you get a good grip on the core language. Focus on how to solve your problems using basic algebraic datatypes (variants, tuples, records), ordinary parametric polymorphism (as opposed to the subtyping you see with polymorphic variants and objects), and modules (but not functors).

Get an understanding of these basic tools before playing around with objects. Most problems you would solve with objects in other languages are solved best in OCaml without them.

zrr