有什么区别!!和 ?在科特林? [英] 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.length
的非空值,或者如果 a
是 null
则抛出一个 NullPointerException:
will return a non-null value of a.length
or throw a NullPointerException if a
is null
:
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
<小时>
总结:
+------------+--------------------+---------------------+----------------------+
| a: String? | a.length | a?.length | a!!.length |
+------------+--------------------+---------------------+----------------------+
| "cat" | Compile time error | 3 | 3 |
| null | Compile time error | null | NullPointerException |
+------------+--------------------+---------------------+----------------------+
可能有用:什么是空指针异常?
这篇关于有什么区别!!和 ?在科特林?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文