Check if there is specific object in kotlin

43 views Asked by At

In my data class I have

public final data class Customer(
    val customerId: String,
    val customerName: String,
    val email: List<Email>?
)

public final data class Email(
    val emailId: String,
    val emailAddress: Set<String?>? = null
)

My function

fun process(incomingCustomer: Customer) {
  //I want to check if incomingCustomer has the email object in it and I have something like
   if(customer.email?.isNullOrEmpty() == true){
     prin("no Email found")
   }
}

I was curious if there is a better way to check if the incomingCustomer has the email object

1

There are 1 answers

0
Vlad Guriev On

fun <T> Collection<T>?.isNullOrEmpty() is an extension function on a nullable type, so you should call it without ?..

email?.isNullOrEmpty() won't be invoked at all if email is null (thus, email?.isNullOrEmpty() == true is false as email?.isNullOrEmpty() is also null)

So, if (customer.email.isNullOrEmpty()) works good in your case