Kotlin(let,with,run,apply,also)函数详解
Kotlin的普及有一段时间了,但对let,with,run,apply,also的函数概念还是不清晰,大部分只是使用let,其他函数使用频率很低。
函数定义
函数名 | 实现 |
---|---|
let | fun T.let(block: (T) -> R): R = block(this) |
with | fun with(receiver: T, block: T.() -> R): R = receiver.block() |
run | fun T.run(block: T.() -> R): R = block() |
apply | fun T.apply(block: T.() -> Unit): T { block(); return this } |
also | fun T.also(block: (T) -> Unit): T { block(this); return this } |
使用场景
网上总结了一个Active图,描述了所有函数的使用场景

1.png
分类
从源码角度来看其实我们可以先简单分为两类
1. 需要返回操作对象
函数名 | 实现 |
---|---|
apply | fun T.apply(block: T.() -> Unit): T { block(); return this } |
also | fun T.also(block: (T) -> Unit): T { block(this); return this } |
2. 需要返回运算结果
函数名 | 实现 |
---|---|
let | fun T.let(block: (T) -> R): R = block(this) |
with | fun with(receiver: T, block: T.() -> R): R = receiver.block() |
run | fun T.run(block: T.() -> R): R = block() |
第二类其实可以简单的理解为let
+with
=run
几个特殊的场景
class User { String name; String nickName; int age; int sex; Address address; Father father; } class Address { String address; int code; } class Father { String name; }
需要返回操作对象
java
if (user != null && user.father != null && user.address != null) { print(user.father.name); print(user.address.address);}
kotlin
user?.apply { print(father?.name) }?address?.apply { print(address) }
需要返回运算结果
java
user.name = "xxx"; user.nickName = "xxx"; user.age = 10; user.sex = 1; if (user.address != null) { user.address.address = "xxx" }
kotlin
var user:User?user?.run{ name = "xxx"; nickName = "xxx"; age = 10; sex = 1; address}?.run { address = "xxx"}
总结
如果不改变返回值使用also
或apply
如果是设置属性值使用apply
或run
,作为参数运算使用also
或let
with
基本可以不用
评论