Use as a singleton

suggest change

Kotlin objects are actually just singletons. Its primary advantage is that you don’t have to use SomeSingleton.INSTANCE to get the instance of the singleton.

In java your singleton looks like this:

public enum SharedRegistry {
    INSTANCE;
    public void register(String key, Object thing) {}
}

public static void main(String[] args) {
    SharedRegistry.INSTANCE.register("a", "apple");
    SharedRegistry.INSTANCE.register("b", "boy");
    SharedRegistry.INSTANCE.register("c", "cat");
    SharedRegistry.INSTANCE.register("d", "dog");
}

In kotlin, the equivalent code is

object SharedRegistry {
    fun register(key: String, thing: Object) {}
}

fun main(Array<String> args) {
    SharedRegistry.register("a", "apple")
    SharedRegistry.register("b", "boy")
    SharedRegistry.register("c", "cat")
    SharedRegistry.register("d", "dog")
}

It’s obvoiusly less verbose to use.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents