使用 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
从这里我们可以注意到:
- 是从 T 对象本身调用,即 T.takeIf;
- predicate 函数将 T 对象作为参数;
- 根据 predicate 的结果最终返回 this 或 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相关推荐
- Kotlin 中的 run、let、with、apply、also、takeIf、takeUnless 语法糖使用和原理分析
这些Kotlin的语法糖函数经常用,但也很容易搞混,所以转载一下,若混了可以回来再看 转载自公众号:纸上浅谈 正文: 在 Kotlin 有一些可以简化代码的语法糖,比如 run.let.with.ap ...
- Kotlin中的高阶函数
博客地址sguotao.top/Kotlin-2018- 在Kotlin中,高阶函数是指将一个函数作为另一个函数的参数或者返回值.如果用f(x).g(x)用来表示两个函数,那么高阶函数可以表示为f(g ...
- [译] Kotlin 中我讨厌什么
(转载)https://juejin.im/entry/594335c18d6d810058ce06a0 阅读 584 收藏 15 2017-06-16 原文链接:github.com 原文地址:Wh ...
- kotlin中继承父属性使用构造方法
kotlin中继承父属性使用构造方法 1. 定义父类,给它两个属性: abstract class AbstractResponseMessage {private var success = tru ...
- Kotlin 中 switch 写法
在Kotlin 中并没有switch 操作符 , 取而代之的是when java的写法: int i= 5;switch (i){case 5:System.out.print("5&quo ...
- kotlin中的异常处理_如何使用assertFailsWith在Kotlin中测试异常
kotlin中的异常处理 by Daniel Newton 丹尼尔·牛顿 如何使用assertFailsWith在Kotlin中测试异常 (How to test exceptions in Kotl ...
- Kotlin中使用简洁明了的代码替换findViewByid
第一种(推荐使用) Kotlin Android 扩展插件(Android Studio 内置) 首先添加 apply plugin: 'kotlin-android-extensions' 官方示例 ...
- Kotlin 中infix,inline,noinline,crossinline ,refied 等的理解
1. infix 的作用 infix 标示的函数可以使用中缀表示法, 中缀表示法就是在写法上可以忽略 . 与 ()并且必须满足三个条件 必须是成员函数或者扩展函数 必须只有一个参数 其参数不能有可变参 ...
- Kotlin中的Java静态方法等效于什么?
本文翻译自:What is the equivalent of Java static methods in Kotlin? There is no static keyword in Kotlin. ...
- 理解 Kotlin 中的属性(property)
这篇文章是一时兴起想写的,因为我发现我对Kotlin的属性理解一直有误 Java 中的属性是什么(property) 首先我们要搞清楚在 Java 中属性是什么,在 Java 中类的属性不是指一个字段 ...
最新文章
- 面向量产的3D目标与车道线检测方法
- wxWidgets:拖放样本
- 【myeclipse】java.lang.NullPointerException at com.genuitec.eclipse.ast.deploy.core.Deployment
- 11月12号 用户登录输入密码错误达到指定次数后,锁定账户 004
- Adobe Illustrator的教程等距购物移动应用程序
- 加强的alert confirm js自定义对话框 多个按钮 ICO自定义
- ES6中Promise的入门(结合例子)
- php 变量 unset,在PHP中unset变量
- 游戏贪吃蛇计分c语言,C语言实现贪吃蛇游戏(命令行)
- fileupload控件的属性_FileUpload控件
- java需要数学_学java要数学好嘛?
- spring 事务传播机制总结
- 按键消抖的Verilog实现
- armbian编译安装mentohust 认证锐捷客户端
- 电气工程和自动化哪个专业就业前景好?
- Java 9 : 从零开始实现模块化(一)
- drupal 7宝典_为Drupal 7建立新主题
- Terminator the Sara Conner Chronicles
- 手把手带你撸一个校园APP(四):APP功能设计及主页面框架
- vue-amap 根据地址 查询经纬度