Kotlin学习笔记(2):run、apply、let、also、with的用法和区别
来源:互联网 发布:一个矩阵怎么计算 编辑:程序博客网 时间:2024/05/23 21:39
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)
运行结果:
run3
用法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)
运行结果:
string3
apply
函数定义:
public inline fun <T> T.apply(block: T.() -> Unit): T { block(); return this }
功能:调用某对象的apply函数,在函数块内可以通过 this 指代该对象。返回值为该对象自己。
示例:
val a = "string".apply { println(this)}println(a)
运行结果:
stringstring
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)
运行结果:
string3
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)
运行结果:
stringstring
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)
运行结果:
string3
参考资料
What’s New in Kotlin 1.1 - also(), takeIf() and takeUnless()[](https://kotlinlang.org/docs/reference/whatsnew11.html#also-takeif-and-takeunless)
- Kotlin学习笔记(2):run、apply、let、also、with的用法和区别
- Kotlin:run、apply、let、also、with的用法和区别
- Kotlin回调的使用以及let、also、with、run、apply函数的用法
- Kotlin基础篇之let、with、run、apply、also函数的使用
- 简述Kotlin中let, apply, run, with的区别
- Koltin-let apply also run with的比较
- Kotlin之let,apply,with,run函数区别
- Kotlin之let,apply,with,run函数区别
- Kotlin之let,apply,with,run函数区别
- Kotlin之let,apply,with,run函数区别
- Kotlin简明学习,标准库中的let,apply,with,run方法
- kotlin 语法分析(五)-- with ,let ,apply
- call和apply的用法和区别
- call和apply的区别和用法
- call和apply的区别和用法
- call和apply的用法和区别
- .apply()用法和call()的区别
- apply()与call()的区别和用法
- String对象
- Freemarker之封装easyUI的datagrid,旨在生成快捷方便的管理列表(一)
- Gulp新手入门教程
- STM32F107——OTG模块之USB设备之虚拟串口移植(三)
- SQL基本语法知识(mysql)
- Kotlin学习笔记(2):run、apply、let、also、with的用法和区别
- mysql高可用之MHA
- 读前辈的大话设计模式(十)之建造者模式,抒自己的读后感
- 3DSlicer12:风格准则
- leetcode--141. Linked List Cycle&&142. Linked List Cycle II
- bootstrap系列之五表单样式
- web容器的会话机制
- Can you answer these queries?(线段树,区间更新,更新到点)
- Simpler