Kotlin:run、apply、let、also、with的用法和区别

run 、 apply 、 let 、 also 和 with 五个函数均位于 kotlin 包下的 Standard 文件中,其含义和用法比较相似,现分别介绍如下。

run

用法1

函数定义:

public inline fun <R> run(block: () -> R): R = block()

功能:调用run函数块。返回值为函数块最后一行,或者指定return表达式。

示例:

val a = run {
    println("run")
    return@run 3
}
println(a)

运行结果:

run
3

用法2

函数定义:

public inline fun <T, R> T.run(block: T.() -> R): R = block()

功能:调用某对象的run函数,在函数块内可以通过 this 指代该对象。返回值为函数块的最后一行或指定return表达式。

示例:

val a = "string".run {
    println(this)
    3
}
println(a)

运行结果:

string
3

apply

函数定义:

public inline fun <T> T.apply(block: T.() -> Unit): T { block(); return this }

功能:调用某对象的apply函数,在函数块内可以通过 this 指代该对象。返回值为该对象自己。

示例:

val a = "string".apply {
    println(this)
}
println(a)

运行结果:

string
string

let

函数定义:

public inline fun <T, R> T.let(block: (T) -> R): R = block(this)

功能:调用某对象的let函数,则该对象为函数的参数。在函数块内可以通过 it 指代该对象。返回值为函数块的最后一行或指定return表达式。

示例:

val a = "string".let {
    println(it)
    3
}
println(a)

运行结果:

string
3

also

函数定义(Kotlin1.1新增的):

public inline fun <T> T.also(block: (T) -> Unit): T { block(this); return this }

功能:调用某对象的also函数,则该对象为函数的参数。在函数块内可以通过 it 指代该对象。返回值为该对象自己。

示例:

val a = "string".also {
    println(it)
}
println(a)

运行结果:

string
string

with

函数定义:

public inline fun <T, R> with(receiver: T, block: T.() -> R): R = receiver.block()

功能:with函数和前面的几个函数使用方式略有不同,因为它不是以扩展的形式存在的。它是将某对象作为函数的参数,在函数块内可以通过 this 指代该对象。返回值为函数块的最后一行或指定return表达式。

示例:

val a = with("string") {
    println(this)
    3
}
println(a)

运行结果:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值