Created
March 11, 2026 13:54
-
-
Save DavidArsene/77b481c4dd6b956678ac811bf0bca750 to your computer and use it in GitHub Desktop.
Set a Kotlin `lateinit var` back to null ;)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (object { | |
| private lateinit var demo: String | |
| fun something() { | |
| demo = "test" | |
| println(demo) // test | |
| // Regular Java reflection, no Kotlin magic, but isn't name safe | |
| uninit("demo") // in `this` | |
| // Requires bundling Kotlin reflection, but no more strings | |
| ::demo.javaField!!.set(this, null) | |
| println(demo) // UninitializedPropertyAccessException | |
| } | |
| }).something() | |
| fun Any.uninit(field: String) = javaClass.getDeclaredField(field).apply { isAccessible = true }.set(this, null) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment