14

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)

lostScriptie
  • 347
  • 1
  • 3
  • 11
  • 1
    This 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 Answers1

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, and null is the result
  • If the value is not null, your function call is made as normal

So, in your case:

  • If somevariable.value is null, the add() call is skipped

  • If somevariable.value is not null, the add() call is made on whatever somevariable.value is

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491