Generics. Part 2

Generic functions

Generic functions can work with any type. Here’s a generic version of the swapTwoInts function from above, called swap:

fun swap<T>(x: T*,y: T*) {
    var temp = x;
    *x = *y;
    *y = *x;
}

The generic version of the function uses a placeholder type name (called T, in this case) instead of an actual type name (such as int, String, or float64). The placeholder type name doesn’t say anything about what T must be, but it does say that both x and y must be of the same type T, whatever T represents. The actual type to use in place of T is determined each time the swap function is called.

The other difference between a generic function and a non generic function is that the generic function’s name (swap) is followed by the placeholder type name (T) inside angle brackets (<T>). The brackets tell Jazz that T is a placeholder type name within the swap function definition.

The swap function can now be called in the same way as swapTwoInts, except that it can be passed two values of any type, as long as both of those values are of the same type as each other. Each time swap is called, the type to use for T is inferred from the types of values passed to the function.

Example:

fun main() {
    var x = 0;
    var y = 42;
    swap(&x,&y); // types inferred automatically to `int`
}

Last updated