hi , any idea why this code snippet doesn't work f...
# android
a
hi , any idea why this code snippet doesn't work for buildString , only currency is evaluated , amount and ratepercent are skipped
Copy code
spannableAmount = SpannableString(buildString {
    currency?.takeIf { it.isNotEmpty() }?.let { currency ->
        currencyLength1 = currency.length
        append("$currency")
    }
    amount?.takeIf { it.isNotEmpty() }?.let { amount ->
        amountLength1 = currencyLength1 + amount.length
        append(" $amount")
    }
    ratePercent?.takeIf { it.isNotEmpty() }?.let { rate ->
        rateLength1 = amountLength1 + rate.length
        append(" $ratePercent")
    }
})
i
Attach a debugger and place some breakpoints
a
it is skipping amount and rate percent, both are non null
i
then break down your call chain to see where it breaks
this code runs correctly online at https://play.kotlinlang.org/
Copy code
fun main() {
    val currency = "eur"
    val amount = "1000"
    val ratePercent = "10"
    var currencyLength1 = 0
    var amountLength1 = 0
    var rateLength1 = 0
    val spannableAmount = buildString {
        currency?.takeIf { it.isNotEmpty() }?.let { currency ->
            currencyLength1 = currency.length
            append("$currency")
        }
        amount?.takeIf { it.isNotEmpty() }?.let { amount ->
            amountLength1 = currencyLength1 + amount.length
            append(" $amount")
        }
        ratePercent?.takeIf { it.isNotEmpty() }?.let { rate ->
            rateLength1 = amountLength1 + rate.length
            append(" $ratePercent")
        }
    }
    println(spannableAmount.toString())
    println(rateLength1)
}
1
a
1. Use a simple if instead of takeIf + let
Copy code
if (currency != null && currency.isNotEmpty()) {
    currencyLength1 = currency.length
    append(currency)
}
2. Nit: instead of using
append(" $amount")
, use two appends --
append(" ")
and
append(amount)
-- to avoid additional string construction