7.9 Classes

Classes are defined using a small language, similar to the modulelanguage.

7.9.1 Class types

Class types are the class-level equivalent of type expressions: theyspecify the general shape and type properties of classes.

class-type::=[[?]label-name:] typexpr -> class-type
class-body-type
class-body-type::=object [( typexpr )] {class-field-spec} end
[[ typexpr {, typexpr} ]] classtype-path
let open module-path in class-body-type
class-field-spec::=inherit class-body-type
val [mutable] [virtual] inst-var-name : typexpr
val virtual mutable inst-var-name : typexpr
method [private] [virtual] method-name : poly-typexpr
method virtual private method-name : poly-typexpr
constraint typexpr = typexpr

See also the following language extensions:attributes andextension nodes.

Simple class expressions

The expression classtype-path is equivalent to the class type bound tothe name classtype-path. Similarly, the expression[typexpr1, … typexprn] classtype-path is equivalent tothe parametric class type bound to the name classtype-path, in whichtype parameters have been instantiated to respectively typexpr1,…typexprn.

Class function type

The class type expression typexpr-> class-type is the type ofclass functions (functions from values to classes) that take asargument a value of type typexpr and return as result a class oftype class-type.

Class body type

The class type expressionobject [(typexpr)] {class-field-spec} endis the type of a class body. It specifies its instance variables andmethods. In this type, typexpr is matched against the self type, thereforeproviding a name for the self type.

A class body will match a class body type if it provides definitionsfor all the components specified in the class body type, and thesedefinitions meet the type requirements given in the class body type.Furthermore, all methods either virtual or public present in the classbody must also be present in the class body type (on the other hand, someinstance variables and concrete private methods may be omitted). Avirtual method will match a concrete method, which makes it possibleto forget its implementation. An immutable instance variable will match amutable instance variable.

Local opens

Local opens are supported in class types since OCaml 4.06.

Inheritance

The inheritance construct inheritclass-body-type provides for inclusion ofmethods and instance variables from other class types.The instance variable and method types from class-body-type are addedinto the current class type.

Instance variable specification

A specification of an instance variable is writtenval [mutable] [virtual] inst-var-name: typexpr, whereinst-var-nameis the name of the instance variable and typexpr its expected type.The flag mutable indicates whether this instance variable can bephysically modified.The flag virtual indicates that this instance variable is notinitialized. It can be initialized later through inheritance.

An instance variable specification will hide any previousspecification of an instance variable of the same name.

Method specification

The specification of a method is writtenmethod [private] method-name: poly-typexpr, wheremethod-name is the name of the method and poly-typexpr itsexpected type, possibly polymorphic. The flag private indicatesthat the method cannot be accessed from outside the object.

The polymorphism may be left implicit in public method specifications:any type variable which is not bound to a class parameter and does notappear elsewhere inside the class specification will be assumed to beuniversal, and made polymorphic in the resulting method type.Writing an explicit polymorphic type will disable this behaviour.

If several specifications are present for the same method, theymust have compatible types.Any non-private specification of a method forces it to be public.

Virtual method specification

A virtual method specification is written method [private]virtualmethod-name: poly-typexpr, where method-name is thename of the method and poly-typexpr its expected type.

Constraints on type parameters

The construct constrainttypexpr1= typexpr2 forces the twotype expressions to be equal. This is typically used to specify typeparameters: in this way, they can be bound to specific typeexpressions.

7.9.2 Class expressions

Class expressions are the class-level equivalent of value expressions:they evaluate to classes, thus providing implementations for thespecifications expressed in class types.

class-expr::=class-path
[ typexpr {, typexpr} ] class-path
( class-expr )
( class-expr : class-type )
class-expr {argument}+
fun {parameter}+ -> class-expr
let [rec] let-binding {and let-binding} in class-expr
object class-body end
let open module-path in class-expr
class-field::=inherit class-expr [as lowercase-ident]
inherit! class-expr [as lowercase-ident]
val [mutable] inst-var-name [: typexpr] = expr
val! [mutable] inst-var-name [: typexpr] = expr
val [mutable] virtual inst-var-name : typexpr
val virtual mutable inst-var-name : typexpr
method [private] method-name {parameter} [: typexpr] = expr
method! [private] method-name {parameter} [: typexpr] = expr
method [private] method-name : poly-typexpr = expr
method! [private] method-name : poly-typexpr = expr
method [private] virtual method-name : poly-typexpr
method virtual private method-name : poly-typexpr
constraint typexpr = typexpr
initializer expr

See also the following language extensions:locally abstract types,attributes andextension nodes.

Simple class expressions

The expression class-path evaluates to the class bound to the nameclass-path. Similarly, the expression[typexpr1, … typexprn] class-pathevaluates to the parametric class bound to the name class-path,in which type parameters have been instantiated respectively totypexpr1, …typexprn.

The expression (class-expr) evaluates to the same module asclass-expr.

The expression (class-expr: class-type) checks thatclass-type matches the type of class-expr (that is, that theimplementation class-expr meets the type specificationclass-type). The whole expression evaluates to the same class asclass-expr, except that all components not specified inclass-type are hidden and can no longer be accessed.

Class application

Class application is denoted by juxtaposition of (possibly labeled)expressions. It denotes the class whose constructor is the firstexpression applied to the given arguments. The arguments areevaluated as for expression application, but the constructor itself willonly be evaluated when objects are created. In particular, side-effectscaused by the application of the constructor will only occur at objectcreation time.

Class function

The expression fun [[?]label-name:] pattern-> class-expr evaluatesto a function from values to classes.When this function is applied to a value v, this value ismatched against the pattern pattern and the result is the result ofthe evaluation of class-expr in the extended environment.

Conversion from functions with default values to functions withpatterns only works identically for class functions as for normalfunctions.

The expression

funparameter1parametern-> class-expr

is a short form for

funparameter1-> … fun parametern-> expr

Local definitions

The let and let rec constructs bind value names locally,as for the core language expressions.

If a local definition occurs at the very beginning of a classdefinition, it will be evaluated when the class is created (just as ifthe definition was outside of the class).Otherwise, it will be evaluated when the object constructor is called.

Local opens

Local opens are supported in class expressions since OCaml 4.06.

Class body

class-body::= [( pattern [: typexpr] )] { class-field }

The expressionobjectclass-bodyend denotesa class body. This is the prototype for an object : it lists theinstance variables and methods of an objet of this class.

A class body is a class value: it is not evaluated at once. Rather,its components are evaluated each time an object is created.

In a class body, the pattern (pattern [:typexpr] ) ismatched against self, therefore providing a binding for self and selftype. Self can only be used in method and initializers.

Self type cannot be a closed object type, so that the class remainsextensible.

Since OCaml 4.01, it is an error if the same method or instancevariable name is defined several times in the same class body.

Inheritance

The inheritance construct inheritclass-expr allows reusingmethods and instance variables from other classes. The classexpression class-expr must evaluate to a class body. The instancevariables, methods and initializers from this class body are addedinto the current class. The addition of a method will override anypreviously defined method of the same name.

An ancestor can be bound by appending aslowercase-identto the inheritance construct. lowercase-ident is not a truevariable and can only be used to select a method, i.e. in an expressionlowercase-ident# method-name. This gives access to themethod method-name as it was defined in the parent class even if it isredefined in the current class.The scope of this ancestor binding is limited to the current class.The ancestor method may be called from a subclass but only indirectly.

Instance variable definition

The definition val [mutable] inst-var-name= expr adds aninstance variable inst-var-name whose initial value is the value ofexpression expr.The flag mutable allows physical modification of this variable bymethods.

An instance variable can only be used in the methods andinitializers that follow its definition.

Since version 3.10, redefinitions of a visible instance variable withthe same name do not create a new variable, but are merged, using thelast value for initialization. They must have identical types andmutability.However, if an instance variable is hidden byomitting it from an interface, it will be kept distinct fromother instance variables with the same name.

Virtual instance variable definition

A variable specification is written val [mutable] virtualinst-var-name: typexpr. It specifies whether the variable ismodifiable, and gives its type.

Virtual instance variables were added in version 3.10.

Method definition

A method definition is written methodmethod-name= expr. Thedefinition of a method overrides any previous definition of thismethod. The method will be public (that is, not private) if any ofthe definition states so.

A private method, methodprivatemethod-name= expr, is amethod that can only be invoked on self (from other methods of thesame object, defined in this class or one of its subclasses). Thisinvocation is performed using the expressionvalue-name# method-name, where value-name is directly bound toself at the beginning of the class definition. Private methods donot appear in object types. A method may have both public and privatedefinitions, but as soon as there is a public one, all subsequentdefinitions will be made public.

Methods may have an explicitly polymorphic type, allowing them to beused polymorphically in programs (even for the same object). Theexplicit declaration may be done in one of three ways: (1) by giving anexplicit polymorphic type in the method definition, immediately afterthe method name, i.e._method [private] method-name: {'ident}+. typexpr= expr; (2) by a forward declaration of the explicit polymorphic typethrough a virtual method definition; (3) by importing such adeclaration through inheritance and/or constraining the type of _self.

Some special expressions are available in method bodies formanipulating instance variables and duplicating self:

expr::=
inst-var-name <- expr
{< [ inst-var-name = expr { ; inst-var-name = expr } [;] ] >}

The expression inst-var-name<- expr modifies in-place the currentobject by replacing the value associated to inst-var-name by thevalue of expr. Of course, this instance variable must have beendeclared mutable.

The expression{<inst-var-name1= expr1; … ; inst-var-namen= exprn>}evaluates to a copy of the current object in which the values ofinstance variables inst-var-name1, …, inst-var-namen havebeen replaced by the values of the corresponding expressions expr1,…, exprn.

Virtual method definition

A method specification is written method [private] virtualmethod-name: poly-typexpr. It specifies whether the method ispublic or private, and gives its type. If the method is intended to bepolymorphic, the type must be explicitly polymorphic.

Explicit overriding

Since Ocaml 3.12, the keywords inherit!, val! and method!have the same semantics as inherit, val and method, butthey additionally require the definition they introduce to beoverriding. Namely, method! requires method-name to be alreadydefined in this class, val! requires inst-var-name to be alreadydefined in this class, and inherit! requires class-expr tooverride some definitions. If no such overriding occurs, an error issignaled.

As a side-effect, these 3 keywords avoid the warnings 7(method override) and 13 (instance variable override).Note that warning 7 is disabled by default.

Constraints on type parameters

The construct constrainttypexpr1= typexpr2 forces the twotype expressions to be equals. This is typically used to specify typeparameters: in that way they can be bound to specific typeexpressions.

Initializers

A class initializer initializerexpr specifies an expression thatwill be evaluated whenever an object is created from the class, onceall its instance variables have been initialized.

7.9.3 Class definitions

class-definition::=class class-binding { and class-binding }
class-binding::=[virtual] [[ type-parameters ]] class-name {parameter} [: class-type] = class-expr
type-parameters::=' ident { , ' ident }

A class definition classclass-binding { andclass-binding } isrecursive. Each class-binding defines a class-name that can beused in the whole expression except for inheritance. It can also beused for inheritance, but only in the definitions that follow its own.

A class binding binds the class name class-name to the value ofexpression class-expr. It also binds the class type class-name tothe type of the class, and defines two type abbreviations :class-name and #class-name. The first one is the type ofobjects of this class, while the second is more general as it unifieswith the type of any object belonging to a subclass (seesection 7.4).

Virtual class

A class must be flagged virtual if one of its methods is virtual (thatis, appears in the class type, but is not actually defined).Objects cannot be created from a virtual class.

Type parameters

The class type parameters correspond to the ones of the class type andof the two type abbreviations defined by the class binding. They mustbe bound to actual types in the class definition using typeconstraints. So that the abbreviations are well-formed, typevariables of the inferred type of the class must either be typeparameters or be bound in the constraint clause.

7.9.4 Class specifications

class-specification::=class class-spec { and class-spec }
class-spec::=[virtual] [[ type-parameters ]] class-name : class-type

This is the counterpart in signatures of class definitions.A class specification matches a class definition if they have the sametype parameters and their types match.

7.9.5 Class type definitions

classtype-definition::=class type classtype-def { and classtype-def }
classtype-def::=[virtual] [[ type-parameters ]] class-name = class-body-type

A class type definition classclass-name= class-body-typedefines an abbreviation class-name for the class body typeclass-body-type. As for class definitions, two type abbreviationsclass-name and #class-name are also defined. The definition canbe parameterized by some type parameters. If any method in the classtype body is virtual, the definition must be flagged virtual.

Two class type definitions match if they have the same type parametersand they expand to matching types.