Zyn0.1.0

Null safety

null means "no value". In Zyn, a variable can only be null if its type says so, with a ? at the end. The type checker makes sure such values are checked before they're used, so a program can't crash because something was unexpectedly null.

#Nullable types

String is always a string. String? is a string or null:

var name: String? = "Ada"
println(name)
name = null
println(name)
Output
Ada
null

A null where the type doesn't allow it is an error, found before the program runs:

var name: String = "Ada"
name = null
Error
Type error: 'name' has type String, so it can't hold null
  --> main.zyn:2:8
  |
2 | name = null
  |        ^

So is using a nullable value as if it were there:

fn nickname(name: String): String? = if name == "Robert" { "Bob" } else { null }

let nick = nickname("Ada")
println(nick.length)
Error
Type error: Cannot use '.length' on a String?, which might be null. Use '?.length' to get null instead, or '??' for a default
  --> main.zyn:4:14
  |
4 | println(nick.length)
  |              ^

#Checking for null

After a check for null, Zyn knows the value is there, and the variable has the non-null type: this is called a smart cast.

fn describe(nick: String?): String {
    if nick != null {
        return "{nick} has {nick.length} letters"   // nick is a String here
    }
    return "no nickname"
}

println(describe("Bob"))
println(describe(null))
Output
Bob has 3 letters
no nickname

An early return works too, and so does &&:

fn shout(text: String?): String {
    if text == null { return "(silence)" }
    return text.uppercase()      // text is a String from here on
}

fn isLong(text: String?): Bool = text != null && text.length > 5

println(shout("hi"))
println(shout(null))
println(isLong("wonderful"))
Output
HI
(silence)
true
Note

Smart casts work for let variables and parameters. A var could have changed since the check, so copy it into a let first.

#Safe calls: ?.

a?.b gives a.b if a isn't null, and null if it is. Safe calls can be chained:

data User(name: String, email: String?)

let users = ["ada": User("Ada", "ada@example.com"), "bob": User("Bob", null)]

println(users["ada"]?.email?.length)
println(users["bob"]?.email?.length)
println(users["eve"]?.name)
Output
15
null
null

#Default values: ??

a ?? b gives a if it isn't null, and otherwise b. Together with ?. it covers most cases:

let ages = ["Ada": 36]
println(ages["Ada"] ?? 0)
println(ages["Bob"] ?? 0)

let input: String? = null
let size = input?.length ?? 0
println(size)
Output
36
0
0

The right side of ?? can also be a panic, for when there's no sensible default (panic has the type Nothing, which fits anywhere):

fn initial(name: String?): Char {
    let n = name ?? panic("a name is needed")
    return n[0]
}
println(initial("Zyn"))
Output
Z

#Where nulls come from

  • Map lookups: map[key] is null when the key isn't there, so its type is V?.
  • Functions that might not find something: find, firstOrNull, toIntOrNull, maxOrNull, ...
  • Your own functions, when their return type ends in ?.
  • Java methods: see Java interop.
let numbers = [4, 8, 15]
let big = numbers.find { it > 10 }
let huge = numbers.find { it > 100 }
println("{big} {huge}")
println("12".toIntOrNull() ?? -1)
Output
15 null
12

#Matching on null

A match on a nullable value can have a null branch, and must cover it:

fn describe(n: Int?): String = match n {
    null -> "nothing"
    0 -> "zero"
    _ -> "the number {n}"
}
println(describe(null))
println(describe(7))
Output
nothing
the number 7