KotlinLeaner
11/17/2022, 10:50 AMinternal fun combineFullName(customerAddress: CustomerAddress?): CustomerAddress? {
val fullName = if (customerAddress?.fullName.isNullOrEmpty()) {
customerAddress?.firstName + " " + customerAddress?.lastName
} else {
customerAddress?.fullName
}
return customerAddress?.copy(fullName = fullName)
}
ThanksJoffrey
11/17/2022, 10:52 AMfullName
in the CustomerAddress
definition? Can it have a value that is not first+last? Or does it always start empty/null and is then set by this function?KotlinLeaner
11/17/2022, 10:56 AMfullName
is a type of String. It has 2 condition.
1st Scenario
fullName
will be null then we need to set first+last.
2nd Scenario
fullName
will not be null then we don't need to set first+last because it has same value in first and last.
Thanksephemient
11/17/2022, 11:14 AMRoukanken
11/17/2022, 11:15 AMCustomerAddress
to the function, as it serves no purpose here. Instead you would be better of using it as a receiver
and turn any callsite of combineFullName(someExpression)
to someExpression?.combineFullName()
getting exact same results
After that it looks pretty good, with small change:
internal fun CustomerAddress.combineFullName(): CustomerAddress {
val fullName = if (fullName.isNullOrEmpty()) {
"$firstName $lastName"
} else {
fullName
}
return copy(fullName = fullName)
}
And yes, it's a bad idea 😛ephemient
11/17/2022, 11:15 AMRoukanken
11/17/2022, 11:16 AMJoffrey
11/17/2022, 11:17 AMfullName
KotlinLeaner
11/17/2022, 11:18 AMfirstName + lastname
in my data class. Thanks for sharing that article. I'll remember in futureKotlinLeaner
11/17/2022, 11:19 AMRoukanken
11/17/2022, 11:21 AMdata class Address(
val first: String,
val last: String,
val full: String = "$first $last"
)
println(Address(first = "first", last = "last"))
println(Address(first = "first", last = "last", full = "weird full name"))
Prints
Address(first=first, last=last, full=first last)
Address(first=first, last=last, full=weird full name)
KotlinLeaner
11/17/2022, 11:22 AMRoukanken
11/17/2022, 11:29 AMnull
if it gets null
- this is the purpose of ?.
operator, you don't really need to handle it in function
Not for individual fields 😛 (and your above code currently does not really handle nullability... for example it would set fullName to "null null"
if it got every field null, but you constructed a class from that)Klitos Kyriacou
11/17/2022, 11:46 AMKotlinLeaner
11/17/2022, 11:53 AM