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

Kotlin中赋值并非表达式,如何强制启用断言?

Enabling Assertion Checks in Kotlin (Alternative to Java's Static Block)

Great question! Kotlin intentionally doesn’t allow assignments as expressions (a deliberate choice to avoid bugs from accidental assignments, a common Java pitfall), so we can’t directly translate that static block. But we can replicate the exact same behavior using Kotlin’s assert function and clever use of side effects in the assertion condition.

Here are a couple of clean, idiomatic approaches:

1. Using also for Concise Side Effects

The core idea is that Kotlin’s assert only executes its condition when assertions are enabled (just like Java’s assert). We can use the also function to toggle a flag variable only when the assertion runs:

class YourClass {
    companion object {
        init {
            var assertsEnabled = false
            // When assertions are enabled, this runs and sets the flag to true
            assert(true.also { assertsEnabled = true })
            // If the flag stays false, assertions are disabled
            if (!assertsEnabled) {
                throw AssertionError("Please enable assertions!")
            }
        }
    }
}
  • The companion object’s init block acts like Java’s static block (runs when the class loads).
  • true.also { assertsEnabled = true } returns true (so the assertion never fails), but triggers the side effect of updating the flag—only if assertions are turned on.
  • If assertions are disabled, the also block never executes, leaving assertsEnabled as false, and we throw the error.

2. Explicit Lambda for Lazy Evaluation

If you prefer more explicit code, use the lambda overload of assert (which is lazily evaluated):

class YourClass {
    companion object {
        init {
            var assertsEnabled = false
            assert({ 
                assertsEnabled = true
                true // Return true to avoid triggering an assertion failure
            }())
            if (!assertsEnabled) {
                throw AssertionError("Please enable assertions!")
            }
        }
    }
}

This works identically: the lambda only runs when assertions are enabled, updating the flag to confirm assertions are active.

Key Notes

  • Just like Java, you need to enable JVM assertions with the -ea (enable assertions) flag when running your program.
  • Kotlin’s assert is tied directly to the JVM’s assertion mechanism, so this behavior matches Java’s exactly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:56:44