Search code examples
kotlinminecraftbukkit

Kotlin object's as an injection point for spigot


I've been using the Kotlin with the Bukkit framework and so far it has been great. I am having one major issue though. Bukkit requires that the main plugin class be a class, so that spigot can create an instance of it.

I am writing a library for Kotlin with the Bukkit framework since it was originally written in Java. The main problem I have is that nearly all methods require an instance of the JavaPlugin class, but I don't want to use dependency injection. Having an object, or static access to the JavaPlugin instance would solve this problem.

Is there any way that I can create some sort of wrapper or something of that nature to delegate the behavior of the class to an object?


Solution

  • You can create a singleton instance, as you cannot use object; Bukkit must construct your JavaPlugin, therefore you can't use a direct singleton. You can implement your own using something similar to this:

    class Plugin : JavaPlugin() {
        companion object {
            lateinit var instance: Plugin
            private set
        }
    
        override fun onEnable() {
            instance = this
        }
    }
    

    This will allow you to call this class somewhat as an object, as long as you put your methods in the companion object

    Plugin.instance.doSomething()
    

    or add methods to that companion object to do something with the instance, instead of getting the instance directly, then you could use the most similar Object syntax

    Plugin.doSomethingWithInstance()
    

    I don't believe there are other solutions to this yet, but this gets pretty close to what you want