static methods and variables in Kotlin?

Update: Anyone (like OP) who just needs a so-called “Singleton”, sometimes called “Service” (except in Android), should simply use Kotlin’s built-in:

object Foo {
    // Done, this already does what OP needed,
    // because the boilerplate codes (like static field and constructor),
    // are taken care of by Kotlin.
}

(Like Roman rightly pointed out in the comment-section.)

Previous answer; If you have (or plan to have) multiple static variables, then continue reading:

The closest thing to Java’s static fields is a companion object. You can find the documentation reference for them here: https://kotlinlang.org/docs/reference/object-declarations.html#companion-objects

Your code in Kotlin would look something like this:

class Foo {

    companion object {
        private lateinit var instance: Foo

        fun get(): Foo {
            return instance;
        }
    }

    init {
        if (instance == null) {
            instance = this
        }
    }

}

If you want your fields/methods to be exposed as static to Java callers, you can apply the @JvmStatic annotation:

class Foo {

    companion object {
        private lateinit var instance: Foo

        @JvmStatic fun get(): Foo {
            return instance;
        }
    }

    init {
        if (instance == null) {
            instance = this
        }
    }

}

Note that @JvmStatic does not need any import (as it’s built-in feature of Kotlin).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)