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)
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:
null
, your function call is ignored, and null
is the
resultnull
, your function call is made as normalSo, 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With