gpt4 book ai didi

通过作用域函数的 Kotlin 字段分配(应用)

转载 作者:行者123 更新时间:2023-12-05 01:54:26 25 4
gpt4 key购买 nike

两个这样的外地作业有什么区别?实际上,第一种方式看起来非常可读,但我在许多代码示例中都遇到过第二种方式。

有什么特殊原因吗?

class Login {

var grantToken = GrantTokenRequest()

fun schema(schema: String) {
this.grantToken.schema = schema
}

}




class Login {

var grantToken = GrantTokenRequest()

fun schema(schema: String) = apply { this.grantToken.schema = schema }


}

最佳答案

区别在于函数 schema 的返回类型。

第一种方式返回Unit

第二种方式返回当前范围内this的类型。在您的情况下,第二种方法将返回 Login 类型,因此是此类的实例。

在“配置对象”的情况下,第二种方法更为惯用。来自 Kotlin docs about apply

The common case for apply is the object configuration. Such calls can be read as “apply the following assignments to the object [and return the object itself].”

第二种方法有用的一个原因是因为它使调用链成为可能。这种“返回此”方法链接的通用术语是 "fluent interface" .

val login = Login()
.schema("...")
.anotherFunctionOnLoginClass(...)
.moreCallChaining(...)

附加说明:不需要在 apply lambda 中使用的 this,因为 apply 已经将 this 设置为 Receiver .代码可以简化为

fun schema(schema: String) = apply { grantToken.schema = schema }

关于通过作用域函数的 Kotlin 字段分配(应用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70613551/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com