Parameterized Classes
Recall from the parametric polymorphism section from before that polymorphism in functional programming allows the same interface to accept multiple parameters/inputs. We can do the same for the interfaces of classes, allowing us to achieve genericity and code reuse.
However, unlike before, where the compiler would attempt to find the most general typing for our functions, we have to declare that our classes allow for generic types. For instance, the following is a class declaration that incorrectly assumes that the compiler will infer the generic typing.
However, unlike before, where the compiler would attempt to find the most general typing for our functions, we have to declare that our classes allow for generic types. For instance, the following is a class declaration that incorrectly assumes that the compiler will infer the generic typing.
class pair x0 y0 =
object
val x = x0
val y = y0
method fst = x
method snd = y
end
;;
Error: Some type variables are unbound in this type:
class pair : 'a -> 'b -> object
val x : 'a val y : 'b
method fst : 'a
method snd : 'b
end
The method fst has type 'a where 'a is unbound
OCaml correctly indicates that pair accepts two inputs of generic type but complains about our methods being generic. We need to inform OCaml (much as we did with rec) that our class will accept our generic inputs. We do this with the square bracket construction [] before the class name.
class ['a,'b] pair (x0: 'a) (y0: 'b) =
object
val x = x0
val y = y0
method fst = x
method snd = y
end
;;
class ['a, 'b] pair :
'a ->
'b -> object val x : 'a val y : 'b method fst : 'a method snd : 'b end
Once we inform OCaml that we know what polymorphism is, OCaml will let us use it! Let's see how.
let it_works = new pair "Hello" [1;2;3];;
val it_works : (string, int list) pair = <obj>
So OCaml will tell us that our new instantiation is a (string, int list) pair. Just like before, we can create a pair of any two types (ike tuples, lists, options, etc.). Exciting!
Inheritance
Cool, now that we've covered this more abstract type of classes and objects, we can see how to apply the concept of inheritance to these objects in OCaml.