TL;DR: Use -Xdebug
(Note the d
is lowercase) compiler option, but ensure it isn't used in production
The reason and previous workarounds for this issue have been explained very nicely in this comment in the corresponding issue. In short, retaining variables could lead to memory leaks in some specific cases, and so it was decided to clean them up as soon as they were not used.
The severity of memory leaks without workarounds is much higher than miserable debuggability with workaround. ... Unfortunately, there is no way to preserve the values of the variables and avoid memory leaks. Thus, the sollution will come in some sort of compiler switch, which disables the bug fix.
With Kotlin 1.8 this exact compiler option has been added: -Xdebug
.
Example for enabling this in maven (a better way could be to use maven profiles to ensure this isn't used in prod):
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<configuration>
<args>
<!-- Disables "x was optimized out" behaviour while debugging coroutines. Do NOT use in prod! -->
<arg>-Xdebug</arg>
</args>
</configuration>
</plugin>
As this essentially disables the fix for possible memory leaks, this should not be used in production. As the official docs warn:
Never use this flag in production: -Xdebug can cause memory leaks.