首页 > 编程知识 正文

kotlin 三目运算符

时间:2023-05-04 18:16:05 阅读:184715 作者:3710

由于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")}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。