Skip to content

Instantly share code, notes, and snippets.

@DavidArsene
Created March 11, 2026 13:54
Show Gist options
  • Select an option

  • Save DavidArsene/77b481c4dd6b956678ac811bf0bca750 to your computer and use it in GitHub Desktop.

Select an option

Save DavidArsene/77b481c4dd6b956678ac811bf0bca750 to your computer and use it in GitHub Desktop.
Set a Kotlin `lateinit var` back to null ;)
(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