Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused about Null Safety in Kotlin

I am new to Kotlin and have read more than one time about Null Safety in Kotlin but I am really confused and do not understand clearly. Can anyone helps me answer questions below:

  1. What does ! character in fun getString(key: String!) mean?

  2. Are names of operators below correct:

?.: Safe call operator

?:: Elvis operator

!!: Sure operator

  1. What does differences between ?: operator and ?.let? When should I use each one?
like image 546
An Nguyen Avatar asked Mar 08 '23 11:03

An Nguyen


1 Answers

The first one that is the single exclamation mark (!) is called the platform type. What it does is that, Kotlin doesn't know how that value will turn out. Whether null or not null so it leaves it to you to decide.

The second one (?.) is a safe-call operator. It allows you to combine a method call and a null check into a single operation.

val x:String?
x="foo"
println(x?.toUpperCase())

The third one (?:) is an Elvis Operator or the Null-Coalescing operator . It provides a default pre-defined value instead of null when used.

fun main(args: Array<String>) {
    val x:String?;
    x=null;
    println(x?:"book".toUpperCase())
}

In this instance, the printed value will be "BOOK" since x is null.

The last one doesn't really have a name. It is usually referred to as Double-bang or Double exclamation mark. What it does is that it throws a null pointer exception when the value is null.

val x:String?;
x=null;
println(x!!.toUpperCase())

This will throw a null pointer exception.

?.let ---> the let function

The let function turns an object on which it is called into a parameter of a function usually expressed using a lambda expression. When used with a safe call operator (?.), the let function conveniently converts a nullable object to an object of a non-nullable type.

Let's say we have this function.

fun ConvertToUpper (word: String) {word.toUpperCase()}

The parameter of ConvertToUpper isn't null so we can't pass a null argument to it.

val newWord: String? = "foo"
ConvertToUpper(newWord)

The above code wouldn't compile because newWord can be null and our ConvertToUpper function doesn't accept a null argument.

We can explicitly solve that using an if expression.

if(newWord != null) ConvertToUpper(newWord)

The let function simplifies this for us by calling the function only is the value passed to it isn't null.

newWord?.let {ConvertToUpper(it)}
like image 134
Alf Moh Avatar answered Mar 26 '23 01:03

Alf Moh