Swift vs Kotlin- Nullability
- Swift has a concept called
Optional
, which means values can be absent (nil) - Kotlin has a concept called
Nullable
, which means that values can be absent (null)
Declaring optional/nullable
- Swift
var name:String?
- Kotlin
var name:String?
Let’s explore how optional/nullable
can be handled in various ways
!
Force unwrap !!
// Swift !
var name:String? = "Swift"
print("Name is \(name!)")
// Koltin !!
var name:String? = "Kotlin"
print("Name is: ${name!!}")
nil coalescing operator ?? Elvis operator ?:
// Swift ??
var name:String? = nil
print("Name is \(name ?? "Swift")")
// Koltin ?:
var name:String? = "Kotlin"
print("Name is: ${name ?: "Kotlin"}")
Check for nullable/optional using the if statement
// Swift if statement
var name:String? = nil
if name != nil {
// Swift is not smart enough here to inference the type of name.
// name is still optional here 🤯
print("Name is \(name ?? "Swift")")
}
// Koltin if statement
var name:String? = "Kotlin"
if(name != null){
// Kotlin is smart enough to infer the type of name here as String 😎
print("Name is: $name")
}
Optional binding(if let) and scope functions(let, also, etc.)
// Swift if let optional binding
var name:String? = nil
if let name = name{
// Here the type of name is String
print("Safe value received: \(name)")
}else{
print("Name is still null")
}
// Koltin's scope function
var name:String? = "Kotlin"
name?.let{nonNullableName->
// Kotlin is smart enough to infer the type of name here as String 😎
print("Name is: $nonNullableName")
}
Chaining
struct Language{
let name:String
}
// Optional object
var swift:Language? = Language(name: "Swift")
// Note here object is nullable not its property
print("Language name:\(swift?.name ?? "Swift")")
data class Language(val name: String)
var kotlin:Language? = Language("Kotlin")
print("Name is: ${kotlin?.name}")
guard let
func getFormattedName(name: String?) -> String{
guard let name = name else {
// fallback name
return "No name found"
}
// only executes if name is not nil
return "Nmae is: \(name)"
}
// call the func and print its result
print("Formatted name: \(getFormattedName(name: nil))")