← Back to lessons

24 Options

Intermediate

Option type is basically a box that either contains a value or is empty. It allows for performing computations which may fail.

In this case, function tail expects an array and return its last element. However if the array is empty, then there is nothing to be returned. Thats why we need an option.

None means that the option is empty.

Some, means that the option contains that value

Option<T> is equivalent to ?T, for shorter syntax.

Here we can see if-let expression that uses pattern matching to unbox an option.

Here we show how tail behaves upon failure.

We also made the tail function generic, however, None is the same no matter the type inside.

options.cj
func tail<T>(arr: Array<T>): Option<T> {
    if (arr.size == 0) {
        return None
    }
    return Some(arr[arr.size - 1])
}

main() {
    var a: ?Int64 = tail([5, 3, 69, 11])

    if (let Some(value) <- a) {
        println(value)
    } else {
        println("Empty List")
    }

    a = tail([])
    if (let Some(value) <- a) {
        println(value)
    } else {
        println("Empty List")
    }

    var b: ?String = tail(["YMCA"])
    if (let Some(value) <- b) {
        println(value)
    } else {
        println("Empty List")
    }
}

// Output:
// 11
// Empty List
// YMCA