Kotlin中赋值并非表达式,如何强制启用断言?
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’sinitblock acts like Java’s static block (runs when the class loads). true.also { assertsEnabled = true }returnstrue(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
alsoblock never executes, leavingassertsEnabledasfalse, 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
assertis tied directly to the JVM’s assertion mechanism, so this behavior matches Java’s exactly.
内容的提问来源于stack exchange,提问作者DodgyCodeException

