miqbaldc
07/30/2021, 3:23 PMUserV1
to UserV2
from our shared prefs
Which one do you prefer?
1️⃣
UserV1
& UserV2
is nullable if fetched from server, but we provide a blank/default value
data class UserV1(status: String? = "", phoneNumber: String? = "", areaCode: Int? = -1)
data class UserV2(
accountInfo: Account? = null,
domicileInfo: Domicile? = null,
)
data class Account(status: String? = "", phoneNumber: String? = "")
data class Domicile(areaCode: Int? = -1)
fun UserV1?.toUserV2() = UserV2(
accountInfo = Account(status = this?.status.orEmpty(), phoneNumber = this?.phoneNumber.orEmpty()),
domicileInfo = Domicile(areaCode = this?.areaCode ?: -1)
)
fun UserV2?.orEmpty() = UserV2()
// wrapping the whole if condition, e.g: (if a else b).orEmpty()
fun findUser() = (if (userV2?.status?.isNullOrBlank() == false) userV2 else userV1.toUserV2()).orEmpty()
2️⃣
UserV1
& UserV2
is nullable if fetched from server, and leave it null (no blank/default value)
data class UserV1(status: String? = null, phoneNumber: String? = null, areaCode: Int? = null)
data class UserV2(
accountInfo: Account? = null,
domicileInfo: Domicile? = null,
)
data class Account(status: String? = null, phoneNumber: String? = null)
data class Domicile(areaCode: Int? = null)
fun UserV1?.toUserV2() = UserV2(
accountInfo = Account(status = this?.status.orEmpty(), phoneNumber = this?.phoneNumber.orEmpty()),
domicileInfo = Domicile(areaCode = this?.areaCode ?: -1)
)
fun UserV2?.orEmpty() = UserV2()
// call the `.orEmpty()` twice, e.g: if a.orEmpty() else b.orEmpty()
fun findUser() = if (userV2?.status?.isNullOrBlank() == false) userV2.orEmpty() else userV1.toUserV2().orEmpty()
Tobias Berger
08/09/2021, 7:24 AM.orEmpty()
/ ?: -1
) in the mapping function.
Also, I'd suggest making accountInfo
and domicileInfo
non-null properties and using an empty object as the default if necessary. That might also save you some null handling later.