Kotlin vs Object Pooling – nullify lateinit variable

Nullable type is a good thing. Until you prevent memory allocation to fight Garbage Collection pauses. I want to nullify lateinit variable - I can't. Or can I?

Nullify lateinit

Sometimes you have to nullify things. There are multiple reasons, most of them is the external code. To reduce amount of work that has to be done by Garbage Collector (even if JVM is doesn't memleak as ActionScript)

Easy "solution" is not to use lateinit at all by making it nullable:

but accessing nullable variable is not convenient. Instead of just using steerable  I would have to write steerable!! .

Use Reflection!

No, well, no. It's too slow. Inspection and stuff. Especially on Android.

There's a more performant way - cache your reflection as bytecode instructions. And there is a library for it - ReflectASM. Let's try it out:

And finally, this is how we achieve nullable lateinit:

If you have to do this in a performant way, that's a choice. I don't expect to find a quicker way than with cached bytecode.