I sometimes see statements like somevariable.value?.add()
What purpose does the question mark serve?
(Sorry, at the time of post I had no idea this was Kotlin, I thought it was java)
Asked
Active
Viewed 1.3k times
14

lostScriptie
- 347
- 1
- 3
- 11
-
1This is not Java code. It's Kotlin. – forpas Nov 23 '18 at 21:34
-
https://kotlinlang.org/docs/reference/null-safety.html – Zoe Nov 24 '18 at 08:36
-
You said in another comment " I haven't delved into Kotlin yet even though I know I should be so" ... Therefore you asked this question before you took the time to look it up. Please do the opposite and try to resolve things on your own with reasonable effort before asking. – Jayson Minard Nov 25 '18 at 14:33
1 Answers
31
Kotlin treats null
as something more than the source of null-pointer exceptions.
In your code snippet, somevariable.value
is of a "nullable type", such as MutableList?
or Axolotl?
. A MutableList
cannot be null
, but a MutableList?
might be null
.
Normally, to call a function on an object, you use a .
.
One option for calling a function on a variable, parameter, or property that is
of a nullable type is to use ?.
. Then, one of two things will happen:
- If the value is
null
, your function call is ignored, andnull
is the result - If the value is not
null
, your function call is made as normal
So, in your case:
If
somevariable.value
isnull
, theadd()
call is skippedIf
somevariable.value
is notnull
, theadd()
call is made on whateversomevariable.value
is

CommonsWare
- 986,068
- 189
- 2,389
- 2,491
-
one possibly should also take `!!` for `@NonNull` into account. – Martin Zeitler Nov 23 '18 at 22:32
-
1there is a book, already: https://kotlinlang.org/docs/reference/null-safety.html – Martin Zeitler Nov 23 '18 at 22:38
-
Thank you - I haven't delved into Kotlin yet even though I know I should be so this check threw me off. I can clearly see the value of Kotlin. – lostScriptie Nov 24 '18 at 17:07