我们什么时候应该在 Kotlin 上使用 run、let、apply、also 和 with 的例子 [英] Example of when should we use run, let, apply, also and with on Kotlin
问题描述
我希望每个函数都有一个很好的例子 run, let, apply, also, with
I wish to have a good example for each function run, let, apply, also, with
我已阅读这篇文章 但还是缺少例子
I have read this article but still lack of an example
推荐答案
所有这些函数都是用于切换当前函数/变量的作用域.它们用于将属于一起的东西放在一个地方(主要是初始化).
All these functions are used for switching the scope of the current function / the variable. They are used to keep things that belong together in one place (mostly initializations).
以下是一些示例:
run
- 返回任何你想要的东西,并将它使用的变量重新定义为 this
run
- returns anything you want and re-scopes the variable it's used on to this
val password: Password = PasswordGenerator().run {
seed = "someString"
hash = {s -> someHash(s)}
hashRepetitions = 1000
generate()
}
密码生成器现在被重新定义为 this
,因此我们可以设置 seed
、hash
和 hashRepetitions
而无需使用变量.generate()
将返回一个 Password
的实例.
The password generator is now rescoped as this
and we can therefore set seed
, hash
and hashRepetitions
without using a variable.
generate()
will return an instance of Password
.
apply
类似,但会返回this
:
val generator = PasswordGenerator().apply {
seed = "someString"
hash = {s -> someHash(s)}
hashRepetitions = 1000
}
val pasword = generator.generate()
这对于替代 Builder 模式特别有用,如果您想重新使用某些配置.
That's particularly useful as a replacement for the Builder pattern, and if you want to re-use certain configurations.
let
- 主要用于避免空检查,但也可用作 run
的替代品.不同之处在于,this
仍将与之前相同,您可以使用 it
访问重新定义范围的变量:
let
- mostly used to avoid null checks, but can also be used as a replacement for run
. The difference is, that this
will still be the same as before and you access the re-scoped variable using it
:
val fruitBasket = ...
apple?.let {
println("adding a ${it.color} apple!")
fruitBasket.add(it)
}
上面的代码只有在它不为空时才会将苹果添加到篮子里.另请注意,it
现在 不再是可选的,因此您不会在这里遇到 NullPointerException(也就是说,您不需要使用 ?.代码>访问其属性)
The code above will add the apple to the basket only if it's not null. Also notice that it
is now not optional anymore so you won't run into a NullPointerException here (aka. you don't need to use ?.
to access its attributes)
also
- 当你想使用 apply
时使用它,但不想隐藏 this
also
- use it when you want to use apply
, but don't want to shadow 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
会引用苹果,而不是 > 到水果篮.
Using apply
here would shadow this
, so that this.weight
would refer to the apple, and not to the fruit basket.
注意:我无耻地从我的博客取材
Note: I shamelessly took the examples from my blog
这篇关于我们什么时候应该在 Kotlin 上使用 run、let、apply、also 和 with 的例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!