0

I've read that using "!!" Instead of "?." In kotlin is not recommended. What is the difference between the 2 when checking for null in variables?

tomerpacific
  • 4,704
  • 13
  • 34
  • 52
  • 2
    `obj?.getSomething()` will return null if `obj` is null, or the result of the method call if `obj` is not null. Whereas `obj!!.getSomething()` will throw an exception if `obj` is null. – Slaw Aug 23 '22 at 04:30
  • Also see https://stackoverflow.com/questions/34342413/what-is-the-kotlin-double-bang-operator – Timothy G. Aug 23 '22 at 04:35
  • And [Kotlin safe calls(.?) vs null chekcs(!!)](https://stackoverflow.com/questions/72380994/kotlin-safe-calls-vs-null-chekcs) – Slaw Aug 23 '22 at 04:36

3 Answers3

5

!! - is a developer's way of telling the compiler, trust me, I know this value will not be null. It is an unsafe way of converting a nullable value to a non nullable type. Unsafe meaning that it can throw a NullPointerException if the value is indeed null.

You can read more about it here.

?. - is a developer's way of telling the compiler that in the case where the value is not null, do the rest of the logic followed after the ?. sign. This way is the safe way to access a nullable type.

You can read more about it here

Timothy G.
  • 6,335
  • 7
  • 30
  • 46
tomerpacific
  • 4,704
  • 13
  • 34
  • 52
  • 1
    I would add that use cases for `!!` are almost always better served with `?: error("X should never be null because ")`. This allows programmers to understand why the previous programmer believed this value couldn't be null, and it allows to understand failures more easily when the invariant does change (and it will) – Joffrey Aug 23 '22 at 07:17
1

"?." and "!!" are not the same. "?." operator also called safe call operator which is used to safely access properties from a nullable object

Refer to this link

Whereas "!!" is called a not-null assertion operator, it forcefully denotes a nullable type as not null. using this operator without any check for null will lead to NullPointerException.

Refer to this link

Sreehari K
  • 887
  • 6
  • 16
0

No both are different.

!! operator is called as double bang operator in kotlin. It means you are forcefully nullable fields as non nullable. It will throw NullPointerException when the particular nullable field is null.

var s :String? = null
var b :String = s!!.lowerCase() // It will throw null pointer exception as you are asserting nullable variable as non null

?. is null safe call operator. It is used for making null safe access to particular field.

var s :String? = null
var b :String? = s?.lowerCase() //Here lowerCase will not execute because you are making safe call only if value is not null.

var s :String? = null
var b :String = b?.lowerCase() ?: ""

Additional thing if you need to b as non null during safecall operator you can use ?: (elvis) operator to have default value if previous safe call statement is null.

Gowtham K K
  • 3,123
  • 1
  • 11
  • 29