Kotlin:申请与合作 [英] Kotlin: Apply vs With

查看:71
本文介绍了Kotlin:申请与合作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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?

推荐答案

有两个区别:

  1. apply接受实例作为接收者,而with要求将实例作为参数传递.在这两种情况下,该实例都将成为一个块内的this.

  1. apply accepts an instance as the receiver while with requires an instance to be passed as an argument. In both cases the instance will become this within a block.

apply返回接收方,而with返回其块内最后一个表达式的结果.

apply returns the receiver and with returns a result of the last expression within its block.

我不确定选择哪种功能会有严格的规定.通常,当您需要对某个对象执行某些操作并将其返回时,可以使用apply.当您需要对某个对象执行某些操作并返回其他一些对象时,可以使用withrun.我更喜欢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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆