Home > Software engineering >  throwing exception in let run clause is thrown when value is not null
throwing exception in let run clause is thrown when value is not null

Time:01-18

I have a null safe operator block as follows, and if the value is null, I want to throw an exception. However, I'm experiencing that whether or not the value is null, the exception is thrown. The call to firebase returns Void, so does it get interpreted as null?

Firebase.auth.currentUser?.let { firebaseUser ->
    Firebase.firestore.collection("mycollection")
                    .document("mycollectionid")
                    .collection("mychild")
                    .document("mychildid")
                    .set(data, SetOptions.merge())
                    .await()
} ?: run {
    throw Exception("currentUser is null")
}

How can I make sure that I throw the error only if the let block doesn't execute?

CodePudding user response:

let returns whatever the lambda returns. await() probably doesn't return anything, which is why the run is executed.

You probably want to replace let with also. This works the same as let except it returns whatever object it is called on instead of the lambda result.

See also Function selection

  •  Tags:  
  • Related