Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android question mark after variable [duplicate]

Tags:

kotlin

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)

like image 952
lostScriptie Avatar asked Nov 23 '18 21:11

lostScriptie


1 Answers

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

like image 146
CommonsWare Avatar answered Sep 19 '22 21:09

CommonsWare