之间有什么区别!和 ?在科特林? [英] What's the difference between !! and ? in Kotlin?
本文介绍了之间有什么区别!和 ?在科特林?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是Kotlin的新手.我想知道下面的代码中这两个!!
和?
之间的区别.
I am new to Kotlin. I want to know the difference between this two !!
and ?
in below code.
下面有两个代码段:第一个使用!!
表示mCurrentDataset
,另一个使用?
表示相同的变量.
Below, there are two snippets: the first uses !!
for mCurrentDataset
and another having ?
for same variable.
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参考书,!!
是NPE爱好者的选择:)
As it said in Kotlin reference, !!
is an option for NPE-lovers :)
a!!.length
如果a
为null
,
将返回非null值a.length
或引发 NullPointerException :
val a: String? = null
print(a!!.length) // >>> NPE: trying to get length of null
a?.length
如果a
不是null
,则返回a.length
,否则返回null
:
returns a.length
if a
is not null
, and null
otherwise:
val a: String? = null
print(a?.length) // >>> null is printed in the console
总结:
To sum up:
+------------+--------------------+---------------------+----------------------+
| a: String? | a.length | a?.length | a!!.length |
+------------+--------------------+---------------------+----------------------+
| "cat" | Compile time error | 3 | 3 |
| null | Compile time error | null | NullPointerException |
+------------+--------------------+---------------------+----------------------+
这篇关于之间有什么区别!和 ?在科特林?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文