Easy Disposable clean-up in LibGDX with Kotlin

I thought I’d share this snippet for making it easier to properly track and clean up Disposables using Kotlin.

In Java, I used to collect all my Disposables in a list as I was creating them so it would be easy to dispose of them properly. For example:

private ArrayList<Disposable> d = new ArrayList<>();

public void create() {
    batch = new SpriteBatch();
    d.add(batch);
    assetManager = new AssetManager();
    d.add(assetManager);
    //... and so on
}

public void dispose() {
   for (Disposable disp : d) disp.dispose();
}

I later made the Disposal utility that’s part of CoveTools to make it even easier, but that tool uses Java reflection, so it doesn’t work with Kotlin properties. So I’m back to my old method of collecting references, but I found a cleaner way to do it with a simple extension method that lets you add items to a list as your instantiating them.

private val d: ArrayList<Disposable> = ArrayList()
private infix fun <E> ArrayList<in E>.ref(item: E?): E? {
    if (item != null) this.add(item)
    return item
}

override fun create() {
    batch = d ref SpriteBatch()
    assetManager = d ref AssetManger()
    //...and so on
}