I am new to Kotlin. I want to know the difference between this two !!
and ?
in below code.
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 }
Example – "!!" and "?" operator in KotlinIt throws a NULL pointer exception instead of breaking the programming logic whenever the variable is NULL. In the following example, the value of "test" is NULL. Hence, Kotlin will throw a NULL pointer exception instead of breaking down the logic.
Equality In Kotlin there are two types of equality: Structural equality ( == - a check for equals() ) Referential equality ( === - two references point to the same object)
In certain computer programming languages, the Elvis operator ?: is a binary operator that returns its first operand if that operand is true , and otherwise evaluates and returns its second operand.
AndroidMobile DevelopmentApps/ApplicationsKotlin. In Kotlin, "!!" is an operator that is known as the double-bang operator. This operator is also known as "not-null assertion operator". This operator is used to convert any value to a non-NULL type value and it throws an exception if the corresponding value is NULL.
As it said in Kotlin reference, !!
is an option for NPE-lovers :)
a!!.length
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
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 | +------------+--------------------+---------------------+----------------------+
Might be useful: What is a NullPointerException?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With