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 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.

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

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相关问答推荐

如何在Kotlin中为两个数据类创建可重用的方法?

新的jOOQ Gradle插件无法正确处理自引用关系

Rabin-Karp字符串匹配的实现(Rolling hash)

init中的NPE抽象函数变量

jlink:在合并模块和 kotlin.stdlib 中打包 kotlin.*

如果带注释的成员未被特定块包围,则发出 IDE 警告

为什么多线程不会使执行更快

Jetpack Compose:当状态从另一个活动改变时强制重组

正则表达式 FindAll 不打印结果 Kotlin

有没有办法重用 Job 实例?

Kotlin - mutableMapOf() 会保留我输入的顺序

Android Room - error: Cannot figure out how to save this field into database

如何在Spring Boot应用程序上启用承载身份验证?

未在IntelliJ IDEA上运行临时文件

API 26 上未显示 Android 通知

如何让数据类在Kotlin中实现接口/扩展超类属性?

如果kotlin已经有了getter和setter,为什么在数据类中有componentN函数?

Kotlin内联属性的用例是什么?

Kotlin,什么时候按map授权?

我应该在哪里调用 MobileAds.initialize()?