Singletons with object keyword

Sometimes, your program has to have only one instance of a certain type. This pattern is known as a singleton. In other languages, you would have to implement this pattern manually, making sure that only one instance of your type gets created. But, Kotlin has language support for creating singletons with the object keyword. Here is an example:

object Singleton {
fun sayMyName() {
println("I'm a singleton")
}
}

This will both declare a Singleton class and create an instance of it. Notice how we haven't defined a constructor. Since the compiler creates an instance for you, if you tried to declare a constructor or create an instance yourself, you'd get a compiler error:

//compiler error
val singleton = Singleton()

If you need to access a member from an object, you can do so by first accessing the object type and then the member you wish to invoke. Here's how to call a function from an object:

Singleton.sayMyName()

Other than not having a constructor, there aren't any differences from normal classes. Objects can have properties and functions; they can also implement interfaces and extend other classes. Here is an object that implements the Runnable interface:

object RunnableSingleton : Runnable {
override fun run() {
println("I'm a runnable singleton")
}
}

Kotlin also allows objects to be declared inside classes; then, they become nested singletons.

Nested objects cannot have an inner keyword; they cannot access members from the outer class. Here is how you would declare an object inside a class:

class Outer {
object Singleton {

}
}

Now, let's see what the compiler does when you declare an object. In the case of our Singleton object from the beginning, the compiler would produce Java bytecode similar to this:

public final class User {

public static final User INSTANCE;

private User() {

}

public void sayMyName() {
System.out.println("I'm a singleton");
}

static {
INSTANCE = new User();
}
}

The compiler creates a public static final field and assigns it an object created inside the static initializer block.

This also tells us how to call an object's members from Java. We need to access the INSTANCE public field first, before accessing any members, like this:

Singleton.INSTANCE.sayMyName();

Finally, if you need to some kind of initialization of your object, you can do it inside the init block. The init block will be called when your object gets constructed:

object SingletonWithInitializer {
var name = ""

init {
name = "Singleton"
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.168.8