althaf
07/14/2021, 6:26 AMvar paymentMethod: String? = null
var result = paymentMethod?.takeIf { !it.isNullOrBlank() } ?: let { "-" }
println("output " + result)
The let part is working fine is android studio . However it is showing error in Community Edition. Is this expected or some strange behavior ?rnett
07/14/2021, 6:35 AMlet
(from the stdlib, unless you have another one defined) has a receiver that isn't present there. Does it compile and run fine?althaf
07/14/2021, 6:36 AMalthaf
07/14/2021, 6:37 AMTobias Berger
07/14/2021, 7:08 AMthis
present at that point. Otherwise there is nothing that could be used as a receiver for let
.
But anyways, that let
makes no sense, just use ?: "-"
directly. If you need more than one expression, I suggest using run
instead or even extract that to another function.althaf
07/14/2021, 7:12 AMalthaf
07/14/2021, 7:12 AMprivate fun getDefaultValueIfNotNullOrEmpty(value: String?): String {
return value?.takeIf { !it.isNullOrBlank() } ?: "-"
}
althaf
07/14/2021, 7:13 AMTobias Berger
07/14/2021, 7:19 AMnull
, because the ?
already takes care of that.
And for some syntactic sugar, you could also write that like this:
private fun String?.orDefault() = this?.takeUnless { it.isBlank() } ?: "-"
and then just call
value.orDefault() // no "?" !
althaf
07/14/2021, 7:22 AM