由于Kotlin没有三目表达式这种写法,一般用if else就可以,但是写起来比较麻烦,于是我便写了个扩展函数,支持Boolean和表达式,感觉还行。如果大家有更好的方案,可以留言。
/** * * @author xunevermore * create on 2021/10/26 18:20 * description: * */fun <T> Boolean?.judge(positiveValue: T, negativeValue: T) = if (this != null && this) positiveValue else negativeValuefun <T> Boolean?.judge(positiveValueProvider: () -> T, negativeValueProvider: () -> T): T = if (this != null && this) positiveValueProvider() else negativeValueProvider()private const val TAG = "BooleanJudgeExt"fun test() { var value: Nothing? = null val a = value.judge(1, 2) Log.i(TAG, "test:$a ") val b = value.judge({ true }, { false }) Log.i(TAG, "test: $b") val x = 0 val c = (x == 1).judge( "x is 1" , "x is not 1" ) Log.i(TAG, "test: $c")}