Wesley Acheson
06/30/2020, 2:56 PMMap<ContactDetailsType, ContactDetails>
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.arjun
06/30/2020, 3:12 PM?. let
on individual fieldsWesley Acheson
06/30/2020, 3:46 PMMayank
06/30/2020, 3:47 PMfun <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/QLf3aV57xJoost Klitsie
07/01/2020, 8:19 AMlistOfNotNull
listOfNotNull(email, phone, mobile, landLine).toMap()
Joost Klitsie
07/01/2020, 8:19 AMfun <K, V> mapOfNotNull(vararg values: Pair<K, V?>): Map<K, V> =
values.mapNotNull { (key, value) -> value?.let { key to value } }.toMap()