我希望为每个函数 run、let、apply 以及 with 提供一个很好的例子
我已阅读 this article但仍然缺乏一个例子
最佳答案
所有这些函数都用于切换当前函数/变量的范围。它们用于将属于一起的事物保存在一个地方(主要是初始化)。
这里有一些例子:
run
- 返回你想要的任何东西并将它使用的变量重新定义为 this
val password: Password = PasswordGenerator().run {
seed = "someString"
hash = {s -> someHash(s)}
hashRepetitions = 1000
generate()
}
密码生成器现在被重新定义为 this
,因此我们可以设置 seed
、hash
和 hashRepetitions
而无需使用变量。
generate()
将返回 Password
的一个实例。
apply
类似,但会返回 this
:
val generator = PasswordGenerator().apply {
seed = "someString"
hash = {s -> someHash(s)}
hashRepetitions = 1000
}
val pasword = generator.generate()
这对于替代 Builder 模式特别有用,如果您想重用某些配置。
let
- 主要用于避免空检查,但也可以用作 run
的替代品。不同之处在于,this
仍将与以前相同,并且您使用 it
访问重新作用域的变量:
val fruitBasket = ...
apple?.let {
println("adding a ${it.color} apple!")
fruitBasket.add(it)
}
只有当苹果不为空时,上面的代码才会将苹果添加到篮子中。另请注意,it
现在 不再是可选的,因此您不会在此处遇到 NullPointerException(也就是您不需要使用 ?。
来访问它的属性)
also
- 当你想使用 apply
但不想影响 this
class FruitBasket {
private var weight = 0
fun addFrom(appleTree: AppleTree) {
val apple = appleTree.pick().also { apple ->
this.weight += apple.weight
add(apple)
}
...
}
...
fun add(fruit: Fruit) = ...
}
在此处使用 apply
会影响 this
,因此 this.weight
将引用苹果,而 不是 到水果篮。
注意:我无耻地举了例子from my blog
关于kotlin - 我们何时应该在 Kotlin 上使用 run、let、apply、also 和 with 的示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45977011/
相关文章:
kotlin - 如何在 kotlin 中检查 "instanceof "类?
generics - 通用扩展类 AND 在 Kotlin 中实现接口(interface)
java - 如何仅通过提供大小来像在 Java 中一样在 Kotlin 中创建数组?
kotlin - Kotlin 中 ArrayList
intellij-idea - IntelliJ 中的 Kotlin Unresolved refe
android-studio - 用于使用 gradle (1.1.2-5) 构建的 kotlin