Is this the correct approach I've got multiple nul...
# announcements
w
Is this the correct approach I've got multiple nullable properties and I'm trying to convert them to a
Map<ContactDetailsType, ContactDetails>
Copy code
val email =  source.customer.customerEmail?.let { Customer.ContactDetailsType.EMAIL to Customer.EmailAddress(it)}
val phone = source.customer.telephone?.let { Customer.ContactDetailsType.GENERAL_PHONE to it.toPhoneNumber() }
val mobile = source.cardholderInfo?.mobilePhone?.let { Customer.ContactDetailsType.MOBILE to it.toPhoneNumber()}
val landLine = source.cardholderInfo?.homePhone?.let { Customer.ContactDetailsType.MOBILE to it.toPhoneNumber()}

val contactDetails: Map<Customer.ContactDetailsType, Customer.ContactDetails> = listOf(email, phone, mobile, landLine).filterNotNull().toMap()
The only reason to convert to a list is filteringNotNull() which I get a warning that is useless in a collection anyway.
a
what if u create a mutable map first and then add entries using
?. let
on individual fields
w
That could work
m
You can create an extension function to filter out nullable values
Copy code
fun <K, V: Any> Map<K, V?>.filterNotNullValues(): Map<K, V> {
    val notNullMap = LinkedHashMap<K, V>()
    for ((key, value) in this) {
        if (value != null) {
            notNullMap[key] = value
        }
    }
    return notNullMap
}
Example: https://pl.kotl.in/QLf3aV57x
👍 1
j
Or use
listOfNotNull
Copy code
listOfNotNull(email, phone, mobile, landLine).toMap()
Or create a mapOfNotNull method
Copy code
fun <K, V> mapOfNotNull(vararg values: Pair<K, V?>): Map<K, V> =
		values.mapNotNull { (key, value) -> value?.let { key to value } }.toMap()