← Back to lessons

23 If Let

Intermediate

The if-let expression first evaluates the expression on the right of <- in the condition. If the value matches the pattern on the left of <-, the if branch is executed. Otherwise, the else branch is executed (which can be omitted).

Class Node, which has member value child which is an option as some Node may not have a child

We make use of while-let to loop through the children of a Node while they exist

if-let.cj
func check(a: ?Int64) {
    if (let Some(value) <- a) {
        println("Operation successful, return value: ${value}")
    } else {
        println("Operation failed")
    }
}

class Node {
    var child: ?Node = None
    Node(let val: Int64) {}
}

main() {
    let first = Option<Int64>.Some(2023)
    let second = Option<Int64>.None
    check(first)
    check(second)

    let ar = Array<Node>(5, {i => Node(i)})
    for (i in 1..5) {
        ar[i - 1].child = Some(ar[i])
    }
    var cur: Node = ar[0]
    while (let Some(next) <- cur.child) {
        println(next.val)
        cur = next
    }
}

// Output:
// Operation successful, return value: 2023
// Operation failed
// 1
// 2
// 3
// 4