在koltlin1.1的标准库中新增加了这么几个方法:also,takeIf, takeUnless
之前我有篇文章讲了let,apply,with,run。Kotlin简明学习,标准库中的let,apply,with,run方法
这篇文章也是对上一篇的补充
also
定义
/**
* Calls the specified function [block] with `this` value as its argument and returns `this` value.
*/
@kotlin.internal.InlineOnly
@SinceKotlin("1.1")
public inline fun <T> T.also(block: (T) -> Unit): T { block(this); return this }
also的定义跟apply很像。接收一个函数,函数的参数是类型T的对象。also扩展方法的返回值也是类型T的对象。
举例
val result = "Hello World".also {
println(this)
println(it)
}
println(result)
打印结果
System.out: com.example.kotlintest.MainActivity@ba61275
System.out: Hello World
System.out: Hello World
上面的代码写在MainActivity的onCreate方法中
在实际开发中我们对TextView对象设置属性的时候我们可以用also扩展方法
官方文档上有一段举例的代码:
fun Block.copy() = Block().also { it.content = this.content }
takeIf
定义
/**
* Returns `this` value if it satisfies the given [predicate] or `null`, if it doesn't.
*/
@kotlin.internal.InlineOnly
@SinceKotlin("1.1")
public inline fun <T> T.takeIf(predicate: (T) -> Boolean): T? = if (predicate(this)) this else null
- takeIf是个扩张方法
- 参数是个方法,(T) -> Boolean,这个方法的参数是类型T的对象,返回值是一个布尔类型
- if (predicate(this)) this else null,这个是方法体。通过predicate这个函数为真,返回对象T,要么返回null
举例
val result = "Hello World".takeIf {
it.length > 1
}
println(result)
打印结果
System.out: Hello World
因为it.length > 1这个关系表达式返回true,所以takIf还是返回当前对象
当表达式换成it.length > 100,打印结果就是null
官网对takeIf举例
val outDirFile = File(outputDir.path).takeIf { it.exists() } ?: return false
// do something with existing outDirFile
val index = input.indexOf(keyword).takeIf { it >= 0 } ?: error("keyword not found")
// do something with index of keyword in input string, given that it's found
takeUnless
定义
/**
* Returns `this` value if it _does not_ satisfy the given [predicate] or `null`, if it does.
*/
@kotlin.internal.InlineOnly
@SinceKotlin("1.1")
public inline fun <T> T.takeUnless(predicate: (T) -> Boolean): T? = if (!predicate(this)) this else null
定义上看,takeIf和takeUnless只是在方法体中的if的判断相反,其他都一样。