Улучшить инфикс isNullOrEmpty - PullRequest
       10

Улучшить инфикс isNullOrEmpty

0 голосов
/ 15 января 2019

Я пытаюсь улучшить код с помощью инфикса:

Рабочий код (но довольно уродливый ...):

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!!
}

Я хочу улучшить читабельность следующим образом:

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
}

Это работает, но я думаю, что это может быть улучшено

1 Ответ

0 голосов
/ 15 января 2019

Это можно упростить так:

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

Вы берете this (takeUnless { } может быть непосредственно вызвано на this в этом случае, потому что расширение), если оно не равно нулю или пусто, и other в противном случае.

Обратите внимание, что у Kotlin уже есть расширения для isNullOrBlank и аналогичных.

...