What is the difference between apply and also. From what I know the following code does the same thing:

apply

val person = Person().apply {
    name = "Tony Stark"
    age = 52
    // More such stuff
}

also

val person = Person().also {
  it.name = "Tony Stark"
  it.age = 52
  // More such stuff
}

有什么区别吗?我应该使用其中一个吗?还有,在某些情况下,一个有效,另一个无效吗?

推荐答案

TL;DR Difference

而且函数采用一个lambda,在该lambda中,使用it(隐式名称)或自定义名称引用调用函数的对象(接收器T).

val person = Person().而且 {
    it.name = "Tony Stark"
}

With 申请, on the other hand, a function literal with receiver is used so inside the passed in lambda you can access the receiver’s members directly, as you see in the following. The receiver can be referenced by this.

val person = Person().申请 {
    name = "Tony Stark"
}

而且

声明:

inline fun <T> T.而且(block: (T) -> Unit): T (source)

调用指定的功能块with 100 (the receiver) value as its argument并返回this(接收器)值.

申请

声明:

inline fun <T> T.申请(block: T.() -> Unit): T (source)

调用指定的函数挡路with 100 value as its receiver并返回this值(接收方).

什么时候用什么

使用示例在本thread节中进行了说明.

Kotlin相关问答推荐

如何在使用Kotlin Coroutines时检测和记录何时出现背压

我可以检测一个函数是否在Kotlin中被递归调用(即,重入)吗?

如何通过更改现有数据类型来执行Android房间数据库迁移?

为什么Kotlin有次构造函数和init块?

如何在 kotlin 中使用带有泛型的密封类

是什么让 Kotlin 中的 String 类能够使用方括号?

关于 Kotlin 函数类型转换的问题

找不到引用的类 kotlin.internal.annotations.AvoidUninitializedObjectCopyingCheck

参考 Kotlin 中的 Java 接口静态字段

kotlin 扩展属性的惰性初始化器中的这个引用

Kotlin:找不到符号类片段或其他 android 类

如何将命令行参数传递给Gradle Kotlin DSL

Kotlin解构when/if语句

创建Spring和#180的实例;Kotlin中的参数化类型引用

Java Integer.MAX_VALUE 与 Kotlin Int.MAX_VALUE

Kotlin lambda 语法混淆

在kotlin中初始化类变量的正确位置是什么

Kotlin中保留的关键字是什么?

在android的默认浏览器 Select 列表中添加我的浏览器?

Kotlin - 错误:Could not find or load main class _DefaultPackage