Vaguely about Null Safety in Kotlin
I'm new to Kotlin and have read about Null Safety in Kotlin several times , but I'm really confused and don't understand clearly, Can anyone help me answer the questions below:
-
What does the symbol
!
in meanfun getString(key: String!)
? -
Are the operator names below correct:
?.
: Safe call operator
?:
: Elvis operator
!!
: Correct operator
- What is the difference between operator
?:
and?.let
? When should I use each of them?
source to share
The first, which is the only one exclamation mark (!)
, is called the platform type . What he does is that Kotlin doesn't know how this value will turn out. Zero or not null, so it leaves it up to you to decide.
The second ( ?.
) is the safe call operator . It allows you to combine method invocation and null validation in one operation.
val x:String?
x="foo"
println(x?.toUpperCase())
The third ( ?:
) is the Elvis Operator or Null-Coalescing Operator . It provides a default value and not null when used.
fun main(args: Array<String>) {
val x:String?;
x=null;
println(x?:"book".toUpperCase())
}
In this case, the printable value will be "BOOK"
, since x
- null
.
The latter has no name. It is commonly referred to as double exclamation point or double exclamation point. What he does is what he chooses null pointer exception
when the value is null
.
val x:String?;
x=null;
println(x!!.toUpperCase())
This will throw a null pointer exception.
?.let
---> let function
The let function turns the object on which it is called into a parameter to a function, usually expressed using a lambda expression. When used with the safe call operator ( ?.
), the let function conveniently converts a nullable object to a non-nullable object.
Let's say we have this feature.
fun ConvertToUpper (word: String) {word.toUpperCase()}
The ConvertToUpper parameter is not null, so we cannot pass a null argument to it.
val newWord: String? = "foo"
ConvertToUpper(newWord)
The above code won't compile because it newWord
might be null and our function ConvertToUpper
doesn't take an argument null
.
We can explicitly decide that using an if statement.
if(newWord != null) ConvertToUpper(newWord)
The let function makes this easier for us by calling the function only if the value passed to it is not null.
newWord?.let {ConvertToUpper(it)}
source to share