我是 Kotlin 的新手。我想知道下面代码中这两个 !!
和 ?
之间的区别。
下面有两个片段:第一个使用 !!
表示 mCurrentDataset
,另一个使用 ?
表示相同的变量。
if(!mCurrentDataset!!.load(mDataSetString.get(mCurrentDataSelectionIndex), STORAGE_TYPE.STORAGE_APPRESOURCE))
{
Log.d("MyActivity","Failed to load data.")
return false
}
if(!mCurrentDataset?.load(mDataSetString.get(mCurrentDataSelectionIndex), STORAGE_TYPE.STORAGE_APPRESOURCE)!!)
{
Log.d("MyActivity","Failed to load data.")
return false
}
最佳答案
正如 Kotlin reference 中所说, !!
是 NPE 爱好者的选择:)
a!!.length
将返回 a.length
的非 null 值,如果 a
为 null
,则抛出 NullPointerException :
val a: String? = null
print(a!!.length) // >>> NPE: trying to get length of null
a?.length
如果 a
不是 null
则返回 a.length
,否则返回 null
:
val a: String? = null
print(a?.length) // >>> null is printed in the console
+------------+--------------------+---------------------+----------------------+
| a: String? | a.length | a?.length | a!!.length |
+------------+--------------------+---------------------+----------------------+
| "cat" | Compile time error | 3 | 3 |
| null | Compile time error | null | NullPointerException |
+------------+--------------------+---------------------+----------------------+
可能有用:What is a NullPointerException?
https://stackoverflow.com/questions/44536114/
相关文章:
kotlin - 警告 : Kotlin runtime JAR files in the clas
loops - 在 Kotlin 中的功能循环中,如何执行 "break"或 "continue"?
android - 房间持久性 : Error:Entities and Pojos must ha
android-studio - Kotlin:为什么 Android Studio 中的大多数变量
android - 当列名相同时,如何表示与 Android Room 的 "many to man
enums - 如何在 Kotlin 中为枚举创建 "static"方法?
kotlin - Kotlin 协程中的挂起函数是什么意思?