Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between !! and ? in Kotlin?

Tags:

kotlin

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 } 
like image 776
paril Avatar asked Jun 14 '17 05:06

paril


People also ask

What is the difference between and operator in Kotlin?

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.

What's the difference between == and === operators in Kotlin?

Equality In Kotlin there are two types of equality: Structural equality ( == - a check for equals() ) Referential equality ( === - two references point to the same object)

What does ?: Mean in Kotlin?

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.

What is double exclamation in Kotlin?

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.


1 Answers

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 

To sum up:

+------------+--------------------+---------------------+----------------------+ | 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?

like image 84
Alexander Romanov Avatar answered Oct 17 '22 23:10

Alexander Romanov