Home > Enterprise >  Null check before using variable in function
Null check before using variable in function

Time:10-21

I am wondering if there is a better way of null checking and assigning value like in this example

val result: Clazz? = if (variable == null) null else someFun(variable)

CodePudding user response:

variable?.let(::someFun)

You can use the Kotlin scope function let .

let is often used for executing a code block only with non-null values. To perform actions on a non-null object, use the safe call operator ?. on it and call let with the actions in its lambda.

So in this case someFun is only called if variable is not null. Otherwise null is returned.

The longer form of this would be:

variable?.let(someFun(it))

where it is the non-null value of variable. However:

If the code block contains a single function with it as an argument, you can use the method reference (::) instead of the lambda:

So we can shorten it to the

variable?.let(::someFun) form

CodePudding user response:

Check here, I hope I have replied... https://kotlinlang.org/docs/null-safety.html#elvis-operator

  • Related