https://kotlinlang.org logo
#getting-started
Title
# getting-started
a

althaf

01/21/2022, 6:38 AM
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

gildor

01/21/2022, 7:12 AM
for what specifically?
assignment if variable is null?
currencyInfo = if (currencyInfo == null) { … } else { currencyInfo }
j

jbnizet

01/21/2022, 7:20 AM
Copy code
currencyInfo = currencyInfo ?: run {
    val assetData =
        JsonParser.getJsonDataFromAsset(context, "country_currency.json").orEmpty()
    Gson().fromJson(assetData, CurrencyInfoResponse::class.java)
}
1
1
g

gildor

01/21/2022, 7:28 AM
In our code base we do not use run for this, imo if/else is more readable and explicit
j

Joffrey

01/21/2022, 8:25 AM
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

Vlad Krava

01/21/2022, 1:10 PM
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