Objects and companion objects

The term singleton refers to a class that contains only one instance during the application life cycle. This instance is globally available for all functions and classes. Compared to Java or other programming languages, Kotlin provides an easier way to create a singleton class using the object keyword:

object singletonClassName {
properties
fun function(){
function body
}
}

The singleton class is similar to other normal classes; it contains properties and functions and can implement interfaces. However, there are a few things that make this class unique:

  • The object keyword is used for class declaration
  • We cannot create an instance of this class
  • We cannot declare a constructor with this class

Let's take an example of a Button class that has one property and one function: 

object MyButton {
var count = 0
fun clickMe() {
println("I have been clicked ${++count} times")
}
}

The object keyword performs two important tasks for us. First, it creates the MyButton class, and then it creates a single instance of this class. This instance can be accessed using the class name:

fun main(args: Array<String>) {
MyButton.clickMe()
MyButton.clickMe()
}

The first call to the clickMe() function will increment the count and display the message. The second call to the clickMe() function will do the same, but this time it will display the count as = 2, because the instance of the class has already been created.

To make this clearer, let's create two different functions and call the clickMe() function from them:

fun click03() {
MyButton.clickMe()
}

fun click04() {
MyButton.clickMe()
}

fun main(args: Array<String>) {
MyButton.clickMe()
MyButton.clickMe()
click03()
click04()
}

Trigger the clickMe function by using the MyButton object function and the click03, click04 functions.

Take a look at the following output:

I have been clicked 1 times
I have been clicked 2 times
I have been clicked 3 times
I have been clicked 4 times

As mentioned earlier, this class only creates one instance that is accessible globally. First, we call the clickMe function from main and then we call it indirectly using two other functions, click03 and click04. The count property increases on each function call because the same instance of the class is used every time. In the next section, we will see how the object class works with inheritance and interfaces. 

..................Content has been hidden....................

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