Kotlin 中的简洁 if else

Concise if else in Kotlin

有没有办法通过用 lambdainfix 或任何东西替换它来删除 snackbar 中的这个 if else 块,使其在认知复杂性中没有 +2 嵌套

else {
snackBarBuilder(
                    activities,
                    "failure",
                    "Sorry, text " + if (classofobj.innerclass.toString() == "1") {
                        "good"
                    } else {
                        "bad"
                    }
                )
    }

您可以定义自己的泛型ternary function:

fun <T> ternary(predicate: () -> Boolean, trueCase: () -> T, falseCase: () -> T) =
    if (predicate()) {
        trueCase()
    } else {
        falseCase()
    }

然后像这样使用它:

ternary({ true }, { "was true" }, { "was false" })
    .also { println(it) } // prints: was true

// or

"Sorry, text " + ternary( { classofobj.innerclass.toString() == "1"} , {"good"}, {"bad"} )

你也可以有一个 infix 变体,但我怀疑它是否使事情更具可读性 它有 some precedence strings attached :

infix fun <T> (() -> Boolean).ternary(tfOptions: List<() -> T>): T =
    when (this()) {
        true -> tfOptions[0]()
        false -> tfOptions[1]()
    }

// and then

val result = { true } ternary listOf({ "was true" }, { "was false" })
println(result) // prints: was true