I have four ArrayList below, I am confusing ArrayList with safe call operator and Not Null Assertion Operator like that, even I know what is the meaning of ? and !! in Kotlin, Any one can explain it for me?, how can I explain those four ArrayList situation? thanks.
ArrayList<User?>?, ArrayList<User?>, ArrayList<User>? and ArrayList<User>
or
ArrayList<String?>?,ArrayList<String?>,ArrayList<String>? and ArrayList<String>
CodePudding user response:
Hope that'll help you clear that out:
var nullableArrayOfNullableItems: ArrayList<User?>?
// you can do that
nullableArrayOfNullableItems = null
// you also can do that
nullableArrayOfNullableItems = arrayOf(null)
var arrayOfNullableItems: ArrayList<User?>
// you CANT do that
arrayOfNullableItems = null
// you can do that
arrayOfNullableItems = arrayOf(null)
var nullableArrayOfNonnullableItems: ArrayList<User>?
// you can do that
nullableArrayOfNonnullableItems = null
// you CANT do that
nullableArrayOfNonnullableItems = arrayOf(null)
var arrayOfNonnullableItems: ArrayList<User>
// you CANT do that
arrayOfNonnullableItems = null
// you CANT do that
arrayOfNonnullableItems = arrayOf(null)
CodePudding user response:
This may explain the four type declarations:
val input = listOf("ArrayList<User?>?",
"ArrayList<User?>",
"ArrayList<User>?",
"ArrayList<User>")
input.forEach {
val arr = it.split(Regex("[<>]"))
val null1 = if (it.endsWith('?')) "nullable" else "not-null"
val null2 = if (arr[1].endsWith('?')) "nullable" else "not-null"
println("$it : $null1 ${arr[0]} with $null2 elements in type ${arr[1].replace(Regex("[?]"),"")}")
}
It prints:
ArrayList<User?>? : nullable ArrayList with nullable elements in type User
ArrayList<User?> : not-null ArrayList with nullable elements in type User
ArrayList<User>? : nullable ArrayList with not-null elements in type User
ArrayList<User> : not-null ArrayList with not-null elements in type User
CodePudding user response:
These uses of ? in a type have nothing to do with safe calls or non-null assertions.
Succinctly:
A ? inside the list type <> like ArrayList<User?> means the list can hold null values.
A ? after the complete type of the list like ArrayList<User>? means the list itself can be null.
Having ? in both places like ArrayList<User?>? means both. It's a list that can hold null values and might be null itself.
Without any question marks, it's a List that is not null and cannot hold null values.
