Kotlin中with与扩展函数T.run的优势对比及选型疑问
with Instead of Always Relying on T.run() in Kotlin? Great question! It’s totally understandable to wonder why we’d ever reach for with when T.run() handles null checks so nicely. Let’s break down the key advantages of with and why it still has a solid place in your Kotlin toolbox:
Slightly cleaner syntax for non-null objects
When you’re 100% sure the object you’re working with isn’t null,withsaves you from typing the object name plus.runevery time. It’s a tiny difference, but it adds up—especially if your object has a long or verbose name. Compare these two snippets:// Using with (cleaner for non-null objects) with(userProfileSettings) { enableDarkMode() setNotificationPreferences(NotificationFrequency.DAILY) syncWithCloud() } // Using run (works, but adds extra characters) userProfileSettings.run { enableDarkMode() setNotificationPreferences(NotificationFrequency.DAILY) syncWithCloud() }For non-null contexts,
withfeels more direct—it immediately signals “we’re operating on this specific object right now” without the extra method call overhead.Clearer semantic intent
withis explicitly designed for grouping operations on a single, known object. When other developers seewith(someObject), they instantly know: “Everything inside this block is about modifying or interacting withsomeObject.” Whilerundoes the same thing, its primary association (for many Kotlin devs) is null safety. Usingwithin non-null cases makes your code’s purpose more explicit and readable at a glance.Consistency with existing codebases
If you’re working on a mature project, chances are you’ll encounterwithin legacy code. Sticking withwithin appropriate non-null scenarios keeps your code aligned with the team’s existing style and avoids unnecessary churn. Plus, some developers simply preferwithfor non-null batch operations out of habit—and that’s a valid reason to keep using it!
Can You Always Use T.run() Instead of with?
Technically? Yes. T.run() can do everything with does (plus null checks). But why make your code more verbose than it needs to be when with is a perfect fit for non-null contexts? It’s all about choosing the right tool for the job: use run when null safety is a concern, and reach for with when you want concise, intent-driven code for a guaranteed non-null object.
内容的提问来源于stack exchange,提问作者DoruAdryan

