Search code examples
kotlinkotlin-null-safety

Validate null while passing parameter to a function in Kotlin


I want to call a function that is accepts only non-Null parameter. However, the parameter that I am passing sometimes could be Null. I am new to Kotlin.

Here you can see in myFirstFunction parameter customerName expects a non-Null value. But object1.object2?.object3?.customerName? can be Null. So my question is how to use let function in this case?

function first () {
   if (State.Active == (status)) {
        secondFunction(
            object1.object2?.object3?.customerName?,
            "String to pass",
            accountId
        )
    } 
}
private fun secondFunction(customerName: String, message: String?, accountNumber: String) {

 // some logic goes here.

}

Solution

  • You can save the customerName in a variable and then call secondFunction if name is not null.

    function first () {
        if (State.Active == (status)) {
            val name = object1.object2?.object3?.customerName
            if(name != null) {
                secondFunction(
                    name,
                    "String to pass",
                    accountId
                )
            }
        } 
    }
    

    Or you can also use the let extension function.

    function first () {
        if (State.Active == (status)) {
            object1.object2?.object3?.customerName?.let { name ->
                secondFunction(
                    name,
                    "String to pass",
                    accountId
                )
            }
        } 
    }