Issue
What if overload some Kotlin operator and use it like this:
// Inits somewhere before usage.
val someStrFromServer: String?
lateinit var myFieldText: TextView
override fun onStart() {
super.onStart()
myFieldText.text = someStrFromServer / R.string.app_none
}
Operator overloading:
operator fun String?.div(resId: Int): String {
return if (this.isNullOrBlank()) {
context.getString(resId)
} else {
this
}
}
Output if someStrFromServer null:
D/DEBUG: None
Output if someStrFromServer not null:
D/DEBUG: someStrFromServer
Does anyone know, if in Kotlin exists a more efficient and short way to handle this? Perhaps, even more, global, like extension function.
Solution
You can do that, but it's not very intuitive because the div is normally used in mathematical calculations only. I'd recommend to use something like
someStrFromServer.takeUnless { it.isNullOrBlank()} ?: context.getString(resId)
Or simplified via extension
fun String?.fallback(resId: Int) = takeUnless { it.isNullOrBlank()} ?: context.getString(resId)
used like this:
myFieldText.text = someStrFromServer.fallback(R.string.app_none)
Answered By - s1m0nw1
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.