How to make Garbage Collector works with NotNull variables?

In java, we usually assign null to a variable to let Garbage Collector works on it, but in Kotlin we can’t assign null to a non-null variable.

In Java, this is legal:

String s = "String";
s = null

But in Kotlin, we can’t write this:

var s = "String"
s = null

How to make garbage collector works with non-null variable?


Use nullable type?

var s: String? = "String"
s = null

I doubt whether the ability to set non-primitive type local variables to null actually makes much difference to the time when they will eventually be garbage collected in Java itself.

It is more likely that the GC won’t kick in until after the method completes when the local variable will have fallen out of scope anyway.

So I don’t think that the inability to set non-nullable variables to null in Kotlin in the hope that they will be garbage collected more quickly will be much of a handicap in practice.

Setting a variable to null does not actually do much garbage collection. The main reason you would do it would be to help with program correctness or to make sure that you don’t keep along a reference to a large unused object around somewhere. It is also helpful for broken garbage collectors. Both JVM and Android should be fine in that regard.

If you have a large buffer of something you can assign it a dummy value (for example emptyList() - which translates to Collections.EMPTY_LIST, a singleton object). Otherwise you just got yourself a nice set of use-after-free problems that garbage collection is supposed to prevent.