function

Array.get

Safely gets a element or nil

struct Array['Element] {
    fun get(self, idx: usize) -> ?'Element {}
}

Overview

This method gets the element at idx from the array, or if there's no such element, returns nil.

Regular array access like array[idx] panics if idx is invalid. By using this method, you can safely pass any idx and not panic the program.

Examples

val fruits = ["Apple", "Banana", "Coconut"]
val fourth: ?String = fruits.get(3)

if fourth == nil {
    print("No 4th element")
}

fruits.get(4) orelse {
    print("No 5th element")
}

Settings

Regular