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

Kotlin中with与扩展函数T.run的优势对比及选型疑问

Why Use 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, with saves you from typing the object name plus .run every 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, with feels more direct—it immediately signals “we’re operating on this specific object right now” without the extra method call overhead.

  • Clearer semantic intent
    with is explicitly designed for grouping operations on a single, known object. When other developers see with(someObject), they instantly know: “Everything inside this block is about modifying or interacting with someObject.” While run does the same thing, its primary association (for many Kotlin devs) is null safety. Using with in 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 encounter with in legacy code. Sticking with with in appropriate non-null scenarios keeps your code aligned with the team’s existing style and avoids unnecessary churn. Plus, some developers simply prefer with for 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:14:29