3.12.1 How it works
Sometimes the same idea works for many types: a box that holds a value, a subroutine that returns what it receives. With a type parameter, written between < and > after the name, a single version is written.
ProgramA subroutine for any type
Subroutine identidad<T>(valor As T) As T
Return valor;
EndSubroutine
Algorithm Identidad
Write identidad(4);
Write identidad(2.5);
Write identidad("hola");
EndAlgorithmOutput
4 2.5 hola
The program finishes normally.
The engine infers the type T in each call from the arguments. Records, classes, interfaces and variants can also be generic:
ProgramA generic box
Record Caja<T>
Define contenido As T;
EndRecord
Subroutine abrir<T>(c As Caja<T>) As T
Return c.contenido;
EndSubroutine
Algorithm Cajas
Define numeros As Caja<Integer> <- Caja(7);
Write abrir(numeros), " ", abrir(Caja("x"));
EndAlgorithmOutput
7 x
The program finishes normally.
At the top, the template Caja with a type slot T. Two arrows lead to two concrete versions, Caja of Integer and Caja of String.
3.12.2 What can be done with a value of type T
Inside the generic, T is opaque: the engine does not know what type it will be, so it only allows copying, passing, returning and storing the value. Adding it, comparing it or writing it is an error in the definition itself, even if every call used numbers.
ProgramComparing two values of type T
Subroutine mayor<T>(a As T, b As T) As T
If a > b Then
Return a;
EndIf
Return b;
EndSubroutine
Algorithm Mayor
Write mayor(1, 2);
EndAlgorithmDiagnostics
incompatibleOperandTypes· error · 2:6 · Incompatible types for operator >
The program finishes with an error.
In short
- A type parameter
<T>lets you write a single version for many types. - The concrete type is inferred in each call or written between
<and>. - Inside the generic,
Tis only copied, passed, returned and stored. - Records, subroutines, classes, interfaces and variants can be generic.