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?.bisNullwhenais, anda.botherwise.a ?? bis whataholds, orbwhen it’sNull.- After
If x != Null,xis its type without the?, and the same goes forWhile,&&,||, and an earlyReturn. 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.
Report an issue with this page or with FutureBlitz on GitHub.