13

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
  • 337
  • 3
  • 10

1 Answers1

29

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
  • 954,112
  • 185
  • 2,315
  • 2,367