Search code examples
kotlininfix-notation

Improve infix isNullOrEmpty


I'm trying to improve some code by using infix :

Working code (but kinda ugly...) :

fun test (possibleEmptyString: String?, anotherPossibleEmptyString : String?): String {
    var test: String? = possibleEmptyString

    // If null or empty
    if(test!=null && !"".equals(test)) {
        test = anotherPossibleEmptyString
    }

    // If null or empty
    if(test!=null && !"".equals(test)) {
        test = "a known string"
    }

    return test!!
}

I want to improve readability like this :

fun test (possibleEmptyString: String?, anotherPossibleEmptyString : String?): String {
    return (possibleEmptyString orIfNullOrEmpty anotherPossibleEmptyString orIfNullOrEmpty "a known string")!!
}

infix fun String?.orIfNullOrEmpty(other: String?): String? {
    if (this != null && !"".equals(this)) {
        return this
    }

    return other
}

It works but i think it can be improve


Solution

  • It can be simplified like this:

    infix fun String?.orIfNullOrEmpty(other: String?) = 
        takeUnless { it.isNullOrBlank() } ?: other
    

    You take this (takeUnless { } can directly be invoked on this in this case, because extension) if it is not null or blank and other otherwise.

    Note that Kotlin already has extensions for isNullOrBlank and similar.