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)
withreturns the result of the last line of code inside its block. For example, if yourwithblock ends withcity = "New York", it will return the string"New York", not the Person object. If you want to get the Person instance back fromwith, you have to explicitly return it (like addingthisas the last line).applyalways returns the object it was called on (the Person instance in our case). This is why we can chainPerson().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,
applyis 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 })
- If you're creating a new object and immediately configuring its properties,
Semantic Meaning
withis more about "performing a set of operations on this object"—it emphasizes the actions you're taking on the instance.applyis 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
applyif 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
withif you already have an existing object and just need to run a series of operations on it (thoughapplyworks here too—person.apply { ... }is also valid!).
内容的提问来源于stack exchange,提问作者sagar suri
相关产品推荐
相关产品推荐

