Generic Enums

In the Cangjie programming language, one of the most commonly used examples of generic enum types is the Option type (see Option Types). The Option type is used to represent a value of some other type that may be present or absent. The absence of a value can be used, for instance, to signify a calculation failure for a numeric type when the specific kind of failure does not matter. Because it is desirable to support the possible value absence for any underlying type, Option is best implemented as a generic type, Option<T>:

package core // `Option` is defined in core.

public enum Option<T> {
      Some(T)
    | None

    public func getOrThrow(): T {
        match (this) {
            case Some(v) => v
            case None => throw NoneValueException()
        }
    }
    ...
}

It is apparent that Option<T> has two constructors: one is Some(T), which indicates that a value is present (a normal result in the calculation example above). The other is None, which would indicate the absence of a result due to a failure. The getOrThrow instance function may be used to obtain the internal value v of a Some(v), or have a NoneValueException thrown if there is no value, i.e. the instance is None.

Assume we want to define a safe division function, because a division calculation may fail. If the divisor is 0, safeDiv returns None, otherwise it returns the result of division wrapped in Some:

func safeDiv(a: Int64, b: Int64): Option<Int64> {
    var res: Option<Int64> = match (b) {
                case 0 => None
                case _ => Some(a/b)
            }
    return res
}

In this way, when the divisor is 0, the function won't throw an arithmetic operation exception during execution.