Koltin简明学习,also,takeIf,takeUnless

在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的判断相反,其他都一样。

Kotlin简明学习—文章列表

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值