Optional values: ?T and nil
A value that may not exist has an optional type, its type with a ? in front: a ?str holds a str, or nil, which means none.
email: ?str = nil
print(email)
email = "ann@example.com"
print(email)Output:
nil
ann@example.comAny type can be optional: ?int, ?str, ?[int], ?Person, ?date. A T can go where a ?T is wanted: a variable, an argument, a field, a list’s element or a result.
Using one: check it first
A ?str may be nil, so it isn’t a str, and using it as one is a compile error:
print(email.upper())email is a ?str and may be nil: check it first (if email != nil { ... }), or give a default (email ?? ...)There are two ways to get the value out. A program can never fail because a value was missing: the compiler sees to that.
if x != nil
Inside if x != nil { ... }, the variable x is a T:
fn shout(name: ?str): str {
if name != nil {
return name.upper()
}
return "NOBODY"
}
print(shout("ann"))
print(shout(nil))Output:
ANN
NOBODYThe same works the other way round: when if x == nil { ... } leaves (with return, throw, skip or stop), x is a T for the rest of the block. That’s the usual shape of a function that needs its value:
fn greet(name: ?str): str {
if name == nil {
return "hello, stranger"
}
return "hello, ${name}"
}
print(greet("Bo"))
print(greet(nil))Output:
hello, Bo
hello, strangerIt also works after && (if age != nil && age > 18), after || (if age == nil || age < 18 { ... } else { age is an int here }), in else, and in while x != nil { ... }.
What the check knows lasts until the variable is given another value: after x = ..., it may be nil again. Inside a loop that gives it a value, it’s checked anew each time.
This works for variables and parameters. A field such as user.email could change in between (a function you call could set it), so check a copy: e: ?str = user.email, then if e != nil { ... }. Or give a default.
?? : a default
x ?? default is x’s value if it isn’t nil, else the default:
nick: ?str = nil
print(nick ?? "anonymous")
counts: [?int] = [3, nil, 5]
total: int = 0
counts.walk(c) {
total = total + (c ?? 0)
}
print(total)Output:
anonymous
8The default is only worked out when it’s needed. a ?? b ?? c takes the first that isn’t nil.
Optional fields
An optional field starts as nil, without a default. It lets an obj refer to another of its own type, which makes linked lists, and a node’s parent:
obj Node {
value: int = 0
next: ?Node
}
list: ?Node = nil
(1..3).walk(i) {
list = Node{value: i, next: list}
}
node: ?Node = list
while node != nil {
print(node.value)
node = node.next
}Output:
3
2
1Two objects that point at each other (a child and its parent) are never freed: see Memory.
JSON: null is nil
Converting between JSON and an obj, null and a missing key give nil, and nil gives null:
obj User {
name: str = ""
nick: ?str
age: ?int
}
data: json = convert("{\"name\": \"Ann\", \"age\": 41}")
u: User = convert(data)
print(u)
print(u.nick ?? "no nick")
out: json = convert(u)
print(out)Output:
User {name: "Ann", nick: nil, age: 41}
no nick
{"name":"Ann","nick":null,"age":41}fill sets an optional field to nil when its key is null.
Details
- An optional value can only be compared with
nil(x == nil,x != nil). After the check, it compares as itsT. printand"${x}"shownilfor none.erroris optional already: writeerror, not?error.??Tisn’t a type: one?is enough.- Optional values can’t be map keys or set elements, and
matchdoesn’t take them: match onx ?? default.