You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin新手提问:给Person对象赋值场景下with与apply函数的区别

Difference between with and apply in Kotlin (for Person object initialization)

Hey there! As someone who's been tinkering with Kotlin for years, I totally get the confusion when first coming across with and apply—they look almost identical on the surface, but their differences matter a lot depending on what you're trying to do. Let's break this down using your Person class example.

First, let's set up the context with code examples:

Example Code

Let's start with your basic Person class:

class Person {
    var name: String = ""
    var age: Int = 0
    var city: String = ""
}

Original property assignment

val person = Person()
person.name = "Alice"
person.age = 30
person.city = "New York"

Using with for assignment

val person = Person()
with(person) {
    name = "Alice"
    age = 30
    city = "New York"
}

Using apply for assignment

val person = Person().apply {
    name = "Alice"
    age = 30
    city = "New York"
}

Key Differences in This Scenario

Now let's dive into what makes these two functions distinct when initializing a Person object:

  • Return Value (The Big One)

    • with returns the result of the last line of code inside its block. For example, if your with block ends with city = "New York", it will return the string "New York", not the Person object. If you want to get the Person instance back from with, you have to explicitly return it (like adding this as the last line).
    • apply always returns the object it was called on (the Person instance in our case). This is why we can chain Person().apply { ... } to create and configure the object in one go—no need to declare the variable first and then modify it.
  • Conciseness for Object Creation

    • If you're creating a new object and immediately configuring its properties, apply is far more concise. The chained syntax lets you avoid extra lines of code for variable declaration before configuration.
    • This becomes even more useful when you need to pass the configured object directly to another function. For example:
      // Smooth with apply
      registerUser(Person().apply {
          name = "Bob"
          age = 25
          city = "London"
      })
      
      // Clunkier with with (requires explicit return)
      registerUser(with(Person()) {
          name = "Bob"
          age = 25
          city = "London"
          this // Must explicitly return the Person object
      })
      
  • Semantic Meaning

    • with is more about "performing a set of operations on this object"—it emphasizes the actions you're taking on the instance.
    • apply is specifically designed for "configuring an object and giving it back"—its semantics align perfectly with initialization and setup tasks, making your code more readable to other developers who'll immediately understand you're setting up the object.

Quick Recap

In the context of initializing a Person object:

  • Use apply if you want to create and configure the object in a single chain, or need the configured object as a return value without extra work.
  • Use with if you already have an existing object and just need to run a series of operations on it (though apply works here too—person.apply { ... } is also valid!).

内容的提问来源于stack exchange,提问作者sagar suri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:42:25