Skip to content

Overview

Often when writing code you want to create similar classes or functions that differ only in the type that they operate on. The classic example of this is collection classes. You want to be able to create an Array that can hold objects of a particular type without creating an IntArray, StringArray, etc. This is where generics step in.

A generic class or method takes type parameters — types that the caller provides, much like a method takes value parameters. Pony uses square brackets for type parameters and parentheses for value parameters, so Foo[U32] creates a Foo whose type parameter is U32, and Foo[U32](42) also passes the value 42 to its constructor.

If you want an array of strings, you write Array[String] and the compiler checks that each element you add is a string. Writing the generic class itself asks more of you. Its methods must work for every type and reference capability the class accepts. Suppose you write a getter that returns a field through a read-only reference to the object. If the field holds an immutable string, you can return that string. If the field holds a mutable string, promising to return a writable reference would let the caller change the string through what began as a read-only reference. You’ll work through that example in Generics and Reference Capabilities.

The following sections cover how to use generics in Pony, how to constrain what types a generic accepts, and how to provide specialized method bodies depending on what the type parameter turns out to be.