hi is there better kotlin idiom for this one ? ```...
# getting-started
a
hi is there better kotlin idiom for this one ?
Copy code
if (currencyInfo == null) {
    val assetData =
        JsonParser.getJsonDataFromAsset(context, "country_currency.json").orEmpty()
    currencyInfo = Gson().fromJson(assetData, CurrencyInfoResponse::class.java)
}
g
for what specifically?
assignment if variable is null?
currencyInfo = if (currencyInfo == null) { … } else { currencyInfo }
j
Copy code
currencyInfo = currencyInfo ?: run {
    val assetData =
        JsonParser.getJsonDataFromAsset(context, "country_currency.json").orEmpty()
    Gson().fromJson(assetData, CurrencyInfoResponse::class.java)
}
1
1
g
In our code base we do not use run for this, imo if/else is more readable and explicit
j
IMO it's better to extract that code to a function, and use Elvis. But using the variable itself in the RHS is a smell IMO, I'd rather initialize it with the correct value and make it val (using Elvis, if, or when expression), or use a different name for the assigned variable
☝️ 4
1
v
it looks more like Java style to me. Agree with @Joffrey, Elvis operator will fit here much better:
Copy code
currencyInfo = currencyInfo ?: getCurrencyInfoFromJson(context, "currency_info.json")
or so
1