Kotlin also let 内联扩展函数
Posted 安果移不动
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Kotlin also let 内联扩展函数相关的知识,希望对你有一定的参考价值。
首先 also 英语是而且的意思 let是允许
also的源码是这样的
@kotlin.internal.InlineOnly
@SinceKotlin("1.1")
public inline fun <T> T.also(block: (T) -> Unit): T
contract
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
block(this)
return this
retrun this操作对象后返回对象。
package com.yzdzy.kotlin.temp
fun main()
val res= "Also".also
println(it.length)
it.replace("Also","狗蛋")
println(res)
输出
4
Also
这点要是切换到let。。。就会返回最后一行的结果
let 源码
/**
* Calls the specified function [block] with `this` value as its argument and returns its result.
*
* For detailed usage information see the documentation for [scope functions](https://kotlinlang.org/docs/reference/scope-functions.html#let).
*/
@kotlin.internal.InlineOnly
public inline fun <T, R> T.let(block: (T) -> R): R
contract
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
return block(this)
代码示例
package com.yzdzy.kotlin.temp
fun main()
val res= "let".let
println(it.length)
it.replace("let","狗蛋")
println(res)
输出
3
狗蛋
以上是关于Kotlin also let 内联扩展函数的主要内容,如果未能解决你的问题,请参考以下文章
Kotlin 内联函数let,with,run,apply,also区别和用法
Kotlin笔记:with/let/run/apply/also区别
Kotlin笔记:with/let/run/apply/also区别
Kotlin笔记:with/let/run/apply/also区别