问题
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:
What does
!
character infun getString(key: String!)
mean?Are names of operators below correct:
?.
: Safe call operator
?:
: Elvis operator
!!
: Sure operator
- What does differences between
?:
operator and?.let
? When should I use each one?
回答1:
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)}
来源:https://stackoverflow.com/questions/45390855/confused-about-null-safety-in-kotlin