Is this the correct approach I've got multiple nul...
# announcements
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.
what if u create a mutable map first and then add entries using
?. let
on individual fields
That could work
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
­čĹŹ 1
Or use
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()