https://kotlinlang.org logo
Title
f

Fré Dumazy

10/05/2017, 10:24 AM
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

nil2l

10/05/2017, 10:32 AM
CharSequence.run { if (isNotBlank()) doSomethingWithThis(this) }
f

Fré Dumazy

10/05/2017, 10:37 AM
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

genovich

10/05/2017, 10:37 AM
CharSequence?.takeIf(CharSequence::isNotBlank)?.let { doSomethingWithThis(it) }
f

Fré Dumazy

10/05/2017, 10:37 AM
then I can just use "my text".useNotBlank { doSomethingWithThis(it) }
g

genovich

10/05/2017, 10:38 AM
You can create your own extension method
f

Fré Dumazy

10/05/2017, 10:39 AM
Thanks, I'll do that!
g

genovich

10/05/2017, 10:41 AM
fun CharSequence?.useNotBlank(block: (CharSequence) -> Unit): CharSequence? =
        this?.takeIf(CharSequence::isNotBlank)?.also(block)
👍 1
@Fré Dumazy
e

elect

10/05/2017, 1:52 PM
fun CharSequence?.doSomethingIfValid() {
   if(this != null && this.isNotBlank())
      doSomethingWithThis(this)
}
CharSequence.doSomethingIfValid()