13. Values that may be missing
In this chapter you will learn:
- the difference between
IntandInt?: the latter may hold a value, ornull; - narrowing: where the compiler believes you have checked for
null; - that only
letbindings, parameters and loop variables narrow, and what to do aboutvars and fields; - that
continueandbreaknarrow too; or_elsefrom@std/nullsand what it means that its fallback is evaluated eagerly;- three deliberate mistakes: using a value without checking, narrowing a
var, and puttingnullinto anInt.
13.1 A value that may be missing: the question-mark type
"A value that may be missing" is one of the most common sources of bugs. Many languages use a special null for it, and you find out at run time that you forgot to check. Sprig writes it into the type: Int always has a value, while Int? may hold an Int or may be null. They are not the same type, and the compiler will not let you use the second as the first.
The find below looks for a target in a list of strings; it returns the position when it finds it, and null when it does not:
func find(words: List[String], target: String) -> Int?:
for i in range(words.size()):
if words[i] == target:
return i
return null
let words: List[String] = ["alpha", "beta"]
let index = find(words, "beta")
if index != null:
print("found at " + index)
else:
print("missing")
let other = find(words, "gamma")
print(other == null)
print(other)found at 1
true
null-> Int?is the result type; the question mark says the function may returnnull: it looks by name and does not always find it.return nullis allowed because the result type carries the question mark. The other way around,let n: Int = nulldoes not compile (13.5 shows it).- In
let index = find(words, "beta"),indexisInt?.wordsis["alpha", "beta"]and"beta"is at position 1, so the function returns 1. - After
if index != null:, inside that branchindexisInt, so it joins a string directly:"found at " + indexprintsfound at 1. This change from "may benull" to "definitely has a value" is called narrowing. find(words, "gamma")finds nothing and returnsnull;other == nullistrue.print(other)printsnull: a nullable value can be printed, and compared withnullor with other values.
How the type of index changes:
| position | type of index | why |
|---|---|---|
let index = find(words, "beta") | Int? | the signature is -> Int? |
inside the if index != null: branch | Int | the check just proved it is not null |
| using it again outside the branch | Int? | the check is only valid inside that branch |
You have met nullable types elsewhere already: the map lookup stock["tea"] in chapter 9 returns Int?, and "12".toIntOrNull() in chapter 4 does too. They all work the same way.
13.2 Deliberate mistake: using a value without checking
let count: Int? = "12".toIntOrNull()
print(count + 1)SPR-TYPE-NULLABLE [TYPE] main.spr:2:7: Operator '+' cannot use a value that may be null (expected non-null operands, actual Int? and Int)
hint: count may be null (Int?): check it first with 'if count != null:', and inside that block it is Int, or give a fallback with or_else from @std/nulls.spr.How to read it:
countis the result ofcount.toIntOrNull(), of typeInt?;- line 2, column 7 is the
+; - the message says
+cannot be used on a value that may benull, with actual typesInt?andInt; - the hint gives two ways out: check with
if count != null:first, or give a fallback withor_elsefrom@std/nulls. Both appear later in this chapter.
String concatenation is the same: in "count " + count, a count of type Int? gives this error; only after the check does it work.
13.3 The four narrowing positions
The compiler does not narrow only inside if != null. It recognizes four common shapes:
# Where narrowing happens: if branches, elif/else, the right of and/or, early return.
func describe(count: Int?, verbose: Bool) -> String:
if count == null:
return "none"
elif verbose:
return "count " + count
else:
return "quiet " + count
func first_positive(value: Int?) -> Bool:
return value != null and value > 0
func label(text: String?) -> String:
if text == null or text.length() == 0:
return "empty"
return text
func double(value: Int?) -> Int:
if value == null:
return 0
return value * 2
let none: Int? = null
print(describe(3, true))
print(describe(none, false))
print(first_positive(5))
print(first_positive(none))
print(label(""))
print(label("hi"))
print(double(21))count 3
none
true
false
empty
hi
42- Early return.
if count == null: return "none"; after that,countis no longer nullable. Bothdescribeanddoubledo this:describe(3, true)passes thecount == nullcheck without returning, so it printscount 3. - Inside an
if x != null:branch — including itselifandelse.describe(none, false)receivesnulland takesreturn "none", printingnone. - The right side of
and. Invalue != null and value > 0, the right side only runs when the left is true, sovaluehas a value there.first_positive(5)istrue,first_positive(none)isfalse. - The right side of
or. Intext == null or text.length() == 0, the right side only runs whentextis notnull.label("")printsempty,label("hi")printshi.
All of this has one condition: the name being checked must be unchangeable — a let binding, a parameter or a loop variable. describe's count is a parameter; double's value is too.
13.4 Deliberate mistake: a var does not narrow
With the same check, a var is refused:
var count: Int? = 3
if count != null:
print(count + 1)SPR-TYPE-NULLABLE [TYPE] main.spr:3:11: Operator '+' cannot use a value that may be null (expected non-null operands, actual Int? and Int)
hint: count may be null (Int?), and a var never narrows: copy it into a let (let current = count), check 'if current != null:', and use current inside that block.Why? A var may have been changed somewhere between the check and the use (for example by a function call that modifies it). The compiler assumes nothing. The fix is the hint's: first let current = count, then check current.
Class fields behave the same way: a field does not narrow either, and the compiler's hint is the same one it gives for a var: copy it into a let first. This is one more reason chapter 3 suggested let as the default.
13.5 Deliberate mistake: putting null into an Int
let n: Int = null
print(n)SPR-TYPE-NULL [TYPE] main.spr:1:14: null is not assignable to Int (initializer); use Int? (expected Int, actual null)- the code is
SPR-TYPE-NULL, at thenullin= null; - the message says
nullis not assignable toIntand gives the fix:use Int?.
let n: Int? = null compiles. To hold null, the type must carry the question mark.
Collection types work the same, and the position of the question mark matters:
List[Int?]: the list itself always exists; its elements may benull;List[Int]?: the list itself may benull; its elements do not.
13.6 continue and break narrow too
Inside a loop, continue and break end the current path, just like an early return. Here are two common patterns:
func first_seen(names: List[String?]) -> String:
for name in names:
if name == null:
continue
return name
return "none"
func sum_until_missing(values: List[Int?]) -> Int:
var total = 0
for value in values:
if value == null:
break
total += value
return total
print(first_seen([null, "Ada", "Bo"]))
print(first_seen([null]))
print(sum_until_missing([1, 2, null, 4]))Ada
none
3first_seenreturns the first name that is notnull. The loop variablenameisString?;if name == null: continueskips thenulls, and inreturn nameafter it,namehas narrowed toString.sum_until_missingadds until it meets anull:if value == null: breakends the loop, andtotal += valuecan only be written after the narrowing.first_seen([null, "Ada", "Bo"])skipsnullon the first round and returns"Ada"on the second.first_seen([null])is allnulland returns"none".sum_until_missing([1, 2, null, 4])reaches 1 + 2 = 3 when it meets thenulland stops, printing3.
Follow first_seen([null, "Ada", "Bo"]):
| round | name | check | next |
|---|---|---|---|
| 1 | null | name == null is true | continue to the next round |
| 2 | "Ada" | it is not null | return "Ada" |
13.7 Giving a default with or_else
When you do not want to write the if, @std/nulls provides or_else(value, fallback): use the value if it has one, otherwise the second argument:
import "@std/nulls.spr" as nulls
let stock: Map[String, Int] = {"tea": 12}
print(nulls.or_else(stock["tea"], 0))
print(nulls.or_else(stock["milk"], 0))
func fallback() -> Int:
print("computing the fallback")
return -1
print(nulls.or_else(5, fallback()))12
0
computing the fallback
5stock["tea"]has 12, soor_elsereturns it;stock["milk"]isnull, so it returns the default 0.- The last two lines carry a point:
fallback()is evaluated beforeor_elseis called, whether or not the first argument isnull. Sonulls.or_else(5, fallback())has the value 5, and still printscomputing the fallbackfirst, then5.
This "eager" evaluation means that if the second argument is expensive, or has a side effect (printing, reading a file), it runs even when the first argument has a value. When you want it computed only when needed, write the if value != null: yourself.
@std/nulls also has require(value, message): it returns the value, and throws an error carrying the message when the value is null. Its signature says throws, which belongs to the next chapter.
Coming from another language?
- Sprig has no
?.,??or?:nullable operators; the check has to be written as anif, so where anullwas handled is visible at a glance. - "Optional value" is a library type in many languages (such as
Optional); Sprig's question mark is built into the language. - Objects returned by Java methods are treated as nullable in Sprig; chapter 21 shows how to work with them.
Summary
T?may benull;Talways has a value; the two are not interchangeable, andnullcannot go into a type without the question mark.- The four narrowing positions: early return, an
if != nullbranch (withelif/else), the right ofand, the right ofor;continueandbreaknarrow too. - Only unchangeable names (
let, parameters, loop variables) narrow; copy avaror a field into aletbefore checking it. - There is no
?.and no??; defaults come fromnulls.or_else(whose second argument is always evaluated), and "must have a value" fromnulls.require.
Exercises
Exercise 1 (returning a nullable value). Write first_long(words: List[String], min: Int) -> String? returning the first word at least min characters long, or null. The caller checks it and prints it.
Answer
func first_long(words: List[String], min: Int) -> String?:
for word in words:
if word.length() >= min:
return word
return null
let found = first_long(["a", "hello", "hi"], 3)
if found != null:
print(found)
else:
print("none")helloExercise 2 (a default for a map lookup). Given a Map[String, Int], use or_else to print the value of an existing key, then 0 for a missing one.
Answer
import "@std/nulls.spr" as nulls
let ages: Map[String, Int] = {"Ada": 36}
print(nulls.or_else(ages["Ada"], 0))
print(nulls.or_else(ages["Bo"], 0))36
0Exercise 3 (skip the nulls). Write sum_known(values: List[Int?]) -> Int adding the values that are not null and skipping the nulls with continue. Check that [1, null, 2, null, 3] gives 6.
Answer
func sum_known(values: List[Int?]) -> Int:
var total = 0
for value in values:
if value == null:
continue
total += value
return total
print(sum_known([1, null, 2, null, 3]))6Exercise 4 (fix the var). This does not compile; make it print 40:
var maybe: Int? = 4
if maybe != null:
print(maybe * 10)Answer
var maybe: Int? = 4
let value = maybe
if value != null:
print(value * 10)40Read maybe into let value = maybe, then check value != null.
Next chapter: Handling errors.
