Indexers

Indexers resemble properties except that their accessors take parameters. Indexers allow instances of a class or valuetype to be indexed just like arrays.

indexer-specification

Specification of Indexers indexer-header procedure-division-header access-modifier statement-block access-modifier statement-block

indexer-header

Syntax of INDEXER-ID type-specifier indexer-id-signatureThe method signature enables you to specify passing parameters and returning items within the header of certain elements. You must omit the procedure division header within the method if you use this signature. access-modifier attribute-clause

Example

In the following example, a class is defined and provided with simple getter and setters as a means of assigning and retrieving values. Square brackets used to access arrays, use 0-based indexing. Round brackets use 1-based indexing.

       class-id SimpleIndexer.
       01 myArray string occurs 100.

       indexer-id string.
       procedure division using by value i as binary-long.
       getter.
           set property-value to myArray[i]
       setter.
           set myArray[i] to property-value
       end indexer.

       end class.

See also the IndexerDemo.cbl in the Indexers sample, available from Start > All Programs > Micro Focus Visual COBOL > Samples , under Language Reference for JVM COBOL (Windows) or $COBDIR/demo (UNIX).

Explicit Indexer Implementation

If the FOR clause is specified, this indexer is an Explicit Interface Member Implementation. The indexer may not be invoked explicitly. It will be invoked implicitly when the corresponding indexer is invoked on an instance of this class which has been cast to the interface type.

Use of explicit interface implementation (via the FOR clause) is particularly useful when the class implements two different interfaces, and these two interfaces have a method with the same signature. In this case, by using the FOR phrase, you can supply two different implementations of the method for the two different interfaces.

For example:

interface-id. "Interface1".
indexer-id string.
procedure division using i as binary-long.
end indexer.
end interface.

interface-id. "Interface2". 
indexer-id string.
procedure division using i as binary-long.
end indexer.
end interface.

class-id TwoIndexers implements type Interface1 type Interface2.

indexer-id string for type Interface1.
...
end indexer.

indexer-id string for type Interface2.
...
end indexer.
end class.