Custom kind of object with external instance management


#1

Often, I find myself creating a class that is similar to an object in that i know that only one instance of it will exist, but it can in fact not be an object, so that I have to store that instance in a global variable and access that instead of using the object access syntax or however it is called. An example would be this:

lateinit var main: Main 
class Main : Application() {

  init {
    main = this
  }

  fun showChangelog() {
    ...
  }

}

and I then refer to it as main.showChangelog(), but instead of exposing a variable, I would like to declare this class in a way that Kotlin knows that there is only one instance, which I manage, so i can refer to it as Main.showChangelog()


#2

On second thought. Companion objects may be a better idea.

What about making Main an object but delegating to a private variable (i.e. lateinit var main: Main)?

Probably not...

Here’s a (very poorly made) example:

fun main(args: Array<String>) {
    mainVariable = Main // This is here just to make the example work...
    Main.showChangelog()
}

interface Application {
    fun showChangelog()
}

var mainVariable: Main = Main // You'd probably want to inject this value...

object Main: Application by mainVariable {
    // Implemented only to make example work...
    override fun showChangelog() {
        print("SHOWING")
    }
}

#3

Why you don’t want to use object? It fits your description very well.


#4

There are 2 issues with object here. First, it happens that I need to create a new instance, but I know that the old instance will be disposed beforehand.

And, if you looked right, the example class subclasses Application. But when working with JavaFX, you must not call the constructor of an Application, but the launch method.