是否有一种方法可以通过用lambda或infix或其他任何方法来删除snackbar中的这个lambda块,从而使它在认知复杂性上没有+2嵌套。
else {
snackBarBuilder(
activities,
"failure",
"Sorry, text " + if (classofobj.innerclass.toString() == "1") {
"good"
} else {
"bad"
}
)
}发布于 2021-04-21 07:05:52
您可以定义自己的通用三元函数。
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变体,但我怀疑它是否会使和更易读--它有一些附加的优先条件:
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 truehttps://stackoverflow.com/questions/67189888
复制相似问题