Search code examples
kotlinextension-methods

How create extension function ifNullOrEmpty?


I want to create a function like ifEmpty() of Kotlin that will also check for null:

ifNullOrEmpty{
  //some code if null or empty
}

How can i do this?

And does anyone know what the code below is called?

: R where C : CharSequence, C : R

Example of Kotlin ifEmpty() function.

@SinceKotlin("1.3")
@kotlin.internal.InlineOnly
public inline fun <C, R> C.ifEmpty(defaultValue: () -> R): R where C : CharSequence, C : R =
    if (isEmpty()) defaultValue() else this

Thanks and have a nice day!


Solution

  • As explained in other answers, you can't create ifNullOrEmpty() with similar generic logic as in ifNull(), because you need @InlineOnly which is currently internal and can be used by stdlib only.

    If you don't mind using internal components and writing code that is potentially not forward-compatible, you can utilize a small hack:

    @Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER")
    @kotlin.internal.InlineOnly
    public inline fun <C, R> C.ifNullOrEmpty(defaultValue: () -> R): R where C : CharSequence, C : R =
        if (isNullOrEmpty()) defaultValue() else this
    

    Alternatively, you can use "less generic" implementation as provided by @Joffrey, which should be sufficient for most use cases.