Contents | Prev | Next | Index


Class Operators

Canterbury Pascal defines two operators, IS and AS, that operate on class and object references.

The IS operator belongs to the group of relational operators. Its purpose is to perform a dynamic type checking. Using the IS operator makes it possible to check whether the actual runtime type of an object reference belongs to a particular class. The syntax of the IS operator is:

ObjectRef IS ClassRef

where ObjectRef is an object reference and ClassRef is the identifier of a class type. The IS operator returns a boolean value. The value is TRUE if ObjectRef is an instance of the class denoted by ClassRef or an instance of a class derived from the class denoted by ClassRef. Otherwise, the result is FALSE. If ObjectRef is NIL, the result is always FALSE. If the declared types of ObjectRef and ClassRef are known not to be related, in particular, the declared type of ObjectRef is known not to be an ancestor of, or equal to, or a descendant of ClassRef, then the compiler reports a type mismatch error.

The IS operator is often used in conjunction with an IF statement to perform a guarded typecast. For example:

IF ActiveControl IS TEdit THEN BEGIN
  TEdit( ActiveControl ).SelectAll;
END;

Here, if the IS test is TRUE, it is safe to typecast ActiveControl to be of class TEdit. Canterbury Pascal always maps the IS operator to Java's instanceof operator.

The AS operator is used to perform checked typecasts. The syntax of the AS operator is:

ObjectRef AS ClassRef

where ObjectRef is an object reference and ClassRef is an identifier of a class type. The resulting value is a reference to the same object as ObjectRef, but with the type given by ClassRef. If during runtime ObjectRef is neither NIL nor an instance of the class denoted by ClassRef nor an instance derived from the class denoted by ClassRef, then a runtime exception is thrown. If the declared types of ObjectRef and ClassRef are known not to be related, then, as in the case of the IS operator, the compiler reports a type mismatch error.

The AS operator is often used in conjunction with a WITH statement. For example:

WITH Sender AS TButton DO BEGIN
  Caption := '&ok';
  OnClick := OkClick;
END;

The AS operator belongs to the precedence group of the multiplying operators. This means that, when used as a variable reference in an expression designator, an AS typecast must be enclosed in parentheses:

(Sender AS TButton).Caption := '&ok';

This compiler always maps the AS operator to a Java class typecast.


Contents | Prev | Next | Index

Canterbury Pascal for JVM  (Last documentation update Sep 02, 2004)
Copyright © 1999-2004 J.Neuhoff - mhccorp.com  . All rights reserved.
Please send any comments or corrections to neuhoff@mhccorp.com