Hi, I was wondering, is there something shorter fo...
# announcements
f
Hi, I was wondering, is there something shorter for
CharSequence.takeIf { it.isNotBlank() }?.let { doSomethingWithThis(it) }
to execute code only if a String or CharSequence is not null or blank?
n
CharSequence.run { if (isNotBlank()) doSomethingWithThis(this) }
f
Perhaps, but I was looking for something less verbose. I had to change to String instead of CharSequence. Eventually I think i'll write an extension function: inline fun String.useNotBlank(block: (String) -> Unit): Boolean { return this.takeIf { it.isNotBlank() }?.let(block) != null }
g
CharSequence?.takeIf(CharSequence::isNotBlank)?.let { doSomethingWithThis(it) }
f
then I can just use "my text".useNotBlank { doSomethingWithThis(it) }
g
You can create your own extension method
f
Thanks, I'll do that!
g
Copy code
fun CharSequence?.useNotBlank(block: (CharSequence) -> Unit): CharSequence? =
        this?.takeIf(CharSequence::isNotBlank)?.also(block)
👍 1
@Fré Dumazy
e
Copy code
fun CharSequence?.doSomethingIfValid() {
   if(this != null && this.isNotBlank())
      doSomethingWithThis(this)
}
CharSequence.doSomethingIfValid()