Swift Optional and Kotlin Nullable— A comparison

Handling the million dollar mistake, null reference is a must in modern programming languages. Both Swift and Kotlin has taken similar yet subtly different approach.

Perhaps sharing both together would give one who has view on one to see the other side would be a good comparison.

By default all variables CANNOT be NULL

In Java, if ever a new class object is instantiate, it could either be null or having some value. i.e.

Integer number = null; // Valid
String letter = null; // Valid

Not so for Kotlin and Swift

The below are invalid for Swift and Kotlin

// Swift
let number: Int = nil; // Invalid
let letter: String = nil; // Invalid
// Kotlin
val number: Int = null; // Invalid
val letter: String = null; // Invalid

Both introduce a new type to store NULL

Optional in Swift

In Swift, the new type is called Optional. The way to declare it is as below

let number: Int? = nil
let letter: String? = nil
print(number) // print `nil`
print(letter) // print `nil`

--

--