admin管理员组文章数量:1794759
使用 Kotlin 中的 takeIf
简评:在 Kotlin 的 标准函数中有个 takeIf 函数,你是否了解这个函数呢?其是否只是漂亮点的 if 语句呢?
先来看一个 takeIf 的例子,理论上你可以把代码中的所有 if 替换成 takeIf(虽然不推荐)。
// Original Code if (status) { doThis() } // Modified Code takeIf { status }?.apply { doThis() }和其他的所有函数一样,takeIf 也有自己合适的使用场景。为了更好的理解,先看看 takeIf 的具体实现:
public inline fun <T> T.takeIf(predicate: (T) -> Boolean): T? = if (predicate(this)) this else null从这里我们可以注意到:
根据以上的特点,我们可以推导出其合适的用法:
1. 因为其由 T 对象本身调用,因此可以更方便的处理 null 值问题:
// Original code if (someObject != null && status) { doThis() } // Improved code someObject?.takeIf{ status }?.apply{ doThis() }2. 因为 predicate 函数以 T 对象本身作为参数,因此也可以很方便的判断对象自身的某个属性是否为 null:
// Original code if (someObject != null && someObject.status) { doThis() } // Better code if (someObject?.status == true) { doThis() } // Improved code someObject?.takeIf{ it.status }?.apply{ doThis() }3. 由于当条件为 true 时,最终结果返回的是 this,因此可以进行链式操作:
val index = input.indexOf(keyword).takeIf { it >= 0 } ?: error("Error") val outFile = File(outputDir.path).takeIf { it.exists() } ?: return false另外,对于 takeIf 的使用有一个需要小心的地方,先看看下面的代码:
// Syntactically still correct. But logically wrong!! someObject?.takeIf{ status }.apply{ doThis() } // The correct one (notice the nullability check ?) someObject?.takeIf{ status }?.apply{ doThis() }第一行中的 doThis() 方法一定会执行而无论 status 是 true 还是 false,因为 doThis() 不是 someObject 中的方法。
这里 takeIf 后的 ? 符是很容易忽视但又非常重要的。
版权声明:本文标题:使用 Kotlin 中的 takeIf 内容由林淑君副主任自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.xiehuijuan.com/baike/1686497546a74135.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论