hi i have a strange behavior from Kotlin both Int...
# announcements
a
hi i have a strange behavior from Kotlin both IntellJ Community Edition and Android Studio is using Kotlin 1.5 ,
Copy code
var 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 ?
r
Seems like IntelliJ is correct there,
let
(from the stdlib, unless you have another one defined) has a receiver that isn't present there. Does it compile and run fine?
a
yes on Android Studio it is working
i'm able to run as well
t
it should be able to run if there is a
this
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.
a
@Tobias Berger ah i get it now, in android studio the let code i gave was inside another lambda , so let was referring the the hosting lambda. Where as in Intellj it was in the main function.
Copy code
private fun getDefaultValueIfNotNullOrEmpty(value: String?): String {
    return value?.takeIf { !it.isNullOrBlank() } ?: "-"
}
from your input this did the trick Thank you @rnett and @Tobias Berger
t
just another hint: inside the lambda you don't need to check for
null
, because the
?
already takes care of that. And for some syntactic sugar, you could also write that like this:
Copy code
private fun String?.orDefault() = this?.takeUnless { it.isBlank() } ?: "-"
and then just call
Copy code
value.orDefault() // no "?" !
👍 1
a
Noted , thank you