我们何时应在Kotlin上使用run,let,apply和with的示例 [英] Example of when should we use run, let, apply, also and with on Kotlin
问题描述
我希望为每个函数的运行提供一个很好的例子,让我们一起应用
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
:
apply
is similar, but it will return 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)
}
上面的代码只有在苹果不为null时,才会将其添加到购物篮中.还要注意,it
现在已经不再是可选的了,因此您在这里不会遇到NullPointerException(aka.您不需要使用?.
来访问其属性)
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和with的示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!