Android kotlin中缀问题

我正在得到一个有趣的问题。 当我调试我的应用程序isResColorIdfalse 。 不幸的是, let函数被触发,并且我看到了logcat上的qwe

 fun drawableTint(context: Context, view: View, colorID: Int, isResColorId: Boolean = true) { try { val wrap = DrawableCompat.wrap(view.background) DrawableCompat.setTint(wrap, isResColorId then let { Timber.d("qwe"); ContextCompat.getColor(context, colorID) } ?: colorID) view.setBackgroundDrawable(wrap) }catch (e: Resources.NotFoundException){ Timber.e(e, "c_id: $colorID coz: $isResColorId") } } infix fun <T> Boolean.then(param: T): T? = if (this) param else null 

logcat的:

 qwe 

要确定发生了什么,你应该在lambda中打印it 。 但是可能发生的情况是:

 isResColorId.then(this.let({...})) ?: colorId 

这意味着let里面的块总是被评估。

如果你不想评估中缀函数的第二个参数,如果第一个参数为false,你应该传递一个lambda而不是一个值:

 inline infix fun <T> Boolean.then(block: () -> T): T? = if (this) block() else null 

但是在这种情况下,我宁愿直接写if (condition) A else B ,而不是返回一个可引用装箱的可为null的值,并强制使用elvis操作符来检查null