Kotlin:申请与合作 [英] Kotlin: Apply vs With
问题描述
with和apply之间有什么区别.据我所知,以下代码具有相同的作用:
What is the difference between with and apply. From what I know the following code does the same thing:
swingElement.apply {
minWidth = ENABLED_COLUMN_WIDTH
maxWidth = ENABLED_COLUMN_WIDTH
preferredWidth = ENABLED_COLUMN_WIDTH
}
with(swingElement) {
minWidth = ENABLED_COLUMN_WIDTH
maxWidth = ENABLED_COLUMN_WIDTH
preferredWidth = ENABLED_COLUMN_WIDTH
}
有什么区别吗?我应该使用另一种吗? 另外,在某些情况下,其中一种会起作用而另一种不会起作用吗?
Is there any difference and should I use one over the other? Also, are there some cases where one would work and the other won't?
推荐答案
有两个区别:
-
apply
接受实例作为接收者,而with
要求将实例作为参数传递.在这两种情况下,该实例都将成为一个块内的this
.
apply
accepts an instance as the receiver whilewith
requires an instance to be passed as an argument. In both cases the instance will becomethis
within a block.
apply
返回接收方,而with
返回其块内最后一个表达式的结果.
apply
returns the receiver and with
returns a result of the last expression within its block.
我不确定选择哪种功能会有严格的规定.通常,当您需要对某个对象执行某些操作并将其返回时,可以使用apply
.当您需要对某个对象执行某些操作并返回其他一些对象时,可以使用with
或run
.我更喜欢run
,因为我认为它更具可读性,但是这是一个品味问题.
I'm not sure there can be some strict rules on which function to choose. Usually you use apply
when you need to do something with an object and return it. And when you need to perform some operations on an object and return some other object you can use either with
or run
. I prefer run
because it's more readable in my opinion but it's a matter of taste.
这篇关于Kotlin:申请与合作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!