Optionals
Also known as: null nil none undefined nullable maybe option optional chaining null pointer exception safe navigation elvis coalescing
● Intermediate5 minBefore this: Records, If LetSpec 2.7
There is no null. A value that may be missing has a type ending in ?, and you must say what happens when it is.
type User {
name: String
}
fn find_user(id: Int) -> User? {
if id == 7 { User(name: "Asha") } else { none }
}
fn main() {
const found = find_user(7)
const missing = find_user(8)
print(found?.name ?? "guest")
print(missing?.name ?? "guest")
if let u = find_user(7) {
print("Found {u.name}")
}
}The program ran and printed:
kavach run optionals-basic.kav
AshaguestFound Asha
User?is aUserornone.?.reads through:found?.nameis the name, ornonewhen there is no user.??gives a value to use instead ofnone.if letruns a block only when the value is there.
Using an optional as if it were surely there is a compile error. The "null pointer exception" of other languages can't happen.
One page for each form
What Kavach does for you
There is no null
A value that may be missing says so in its type,
User?, and the compiler makes you handle the missing case. A null pointer error can't happen.