Kotlin:应用与使用 [英] Kotlin: Apply vs With

查看:23
本文介绍了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天全站免登陆