Kotlin Singletons

Singleton objects is a design pattern that allows for one and only one instance of a class to exist at a time. Singletons are useful when declaring classes that manage a single shared resource such as a logging file or a network connection. We can use a single object to work with such a resource as opposed to have a bunch of objects in memory that needs synchronized access instead.

Kotlin uses object expressions to create singletons. When we declare an object expression at the top level of a Kotlin module, it becomes a singleton. Here is an example.

object Bob {
    val fName = "Bob"
    val lName = "Belcher"

    fun cook(burgerName : String){
        println("Cooking $burgerName")
    }
}

Many readers will notice that the definition of this Bob object looks almost exactly like a class. That is indeed the case as a matter of fact, only we replace the class keyword with object instead.

We can use a singleton by using the object name followed by a method or property.

fun main(args : Array<String>){
    Bob.cook("Pear Goes the Neighborhood")
}

As a matter of fact, Bob is a global object and is used like any other variable. Developers who are familiar with Java may think of these as static methods, but that is not the case. Static methods are associated with a class. In this case, Bob is actually an instance of a Bob class. His methods belong to an instance, not a class itself.

Since Bob is a singleton, he has some rules. We are free to assign Bob to other variables, but we can’t make more Bob’s (he wouldn’t be a singleton otherwise). Bob also has to be initialized right away with a no-argument constructor (after all, he is created by the runtime). Besides those rules, we use singletons just like any other objects. For example, we could have Bob extend classes or even implement interfaces.

By making Bob a singleton, we are ensuring that only one instance of Bob exists in memory. We are free to use singleton objects just like any other Kotlin object, but we are not free to make new instances of a singleton. Singletons are useful for controlling access to shared resources such as thread pools, logging, caching, or other shared resources. Kotlin makes creating singletons easy by using object expressions.

Putting it Together

Here is a demonstration of singletons followed by program output.

object Bob {
    val fName = "Bob"
    val lName = "Belcher"

    fun cook(burgerName : String){
        println("Cooking $burgerName")
    }
}

fun main(args : Array<String>){
    Bob.cook("Pear Goes the Neighborhood")
}

Output

Cooking Pear Goes the Neighborhood
Advertisements

Kotlin Koans—Part 11

This portion of the Kotlin Koans tutorial focuses on Object Expressions. Practically speaking, Object Expressions serve the same role as anonymous innner classes in Java. They let us make modifications on a class in one particular case without having to create an entirely new class.

This portion of the tutorial has developers creating a dynamic Comparator class that sorts numbers in descending order.

fun task10(): List {
    val arrayList = arrayListOf(1, 5, 2)
    Collections.sort(arrayList, object: Comparator {
        override fun compare(o1: Int?, o2: Int?): Int {
            return o2?.compareTo(o1 ?: 0) ?: 0
        }
    })
    return arrayList
}

We could have used a lambda in this case, but that would miss the point of what the tutorial is trying to teach. In this code snippet, the second paramter of Collections.sort is an Object Expression that defines a custom Comparator class.

You’ll notice that the definition of compare is full of null safe expressions as indicated the by ? and ?: opeartors. As a side note, I really like how Kotlin has an arrayListOf() function that let’s you create an ArrayList. Sure it does the same thing as Arrays.asList, but again, it’s more concise.

You can view part 10 here