Skip to content
FutureBlitz

    Install

    The tour, 7 of 11

    Nullability

    Types that can't be Null unless they say so, and the operators for the ones that can.

    No type holds Null unless it says so with a ?: a Enemy is always an Enemy, and an Enemy? is one or Null. The compiler won’t let code use an Enemy? as an Enemy until it has checked.

    Import std.core
    
    Class Enemy
        Field name: String
    
        New(name: String)
            Self.name = name
        End New
    End Class
    
    Function Nearest(enemies: Enemy[]): Enemy?
        If enemies.Count == 0 Then Return Null
        Return enemies[0]
    End Function
    
    Local target = Nearest([Enemy("bat"), Enemy("rat")])
    If target != Null
        Print("aiming at {target.name}")      // target is an Enemy here
    End If
    
    Local nobody = Nearest([])
    Print(nobody?.name ?? "nothing to aim at")
    Output
    aiming at bat
    nothing to aim at
    • a?.b is Null when a is, and a.b otherwise.
    • a ?? b is what a holds, or b when it’s Null.
    • After If x != Null, x is its type without the ?, and the same goes for While, &&, ||, and an early Return.
    • x.Expect("message") gives the value, or panics with the message where it’s called.
    Import std.core
    
    Local ages = {"Ada": 36, "Alan": 41}
    
    Local ada = ages.Get("Ada")
    If ada == Null Then Print("no Ada")
    Print(ada.Expect("Ada is in the map") + 1)
    
    Local bob = ages.Get("Bob") ?? 0
    Print(bob)
    Output
    37
    0

    Next: errors.

    Next: Errors

    Report an issue with this page or with FutureBlitz on GitHub.