Kotlin Object Keyword

Let's Get The Job Done!

Kotlin Object Keyword

In this post we are gonna find out what is the Object keyword in Kotlin and discuss it’s use-cases. in one definition the Object is another way to declare classes but with some differences, the most important difference is that defining an object makes it act like a singleton object, also by defining an object you could use it’s methods and fields as static. in fact the Object is a keyword for multiple approaches to solve our daily challenges in Kotlin, so let’s dive into the usages of this keyword.

Singleton, just one line: In kotlin you could define a singleton class with just declaring it as Object, as easy as it sounds!

object Singleton {

    fun doWhatEver(){
        // logic here...
    }

}

Let’s compare the code above with java Singleton:

public class ThreadSafeSingleton {

    private static ThreadSafeSingleton instance;
    
    private ThreadSafeSingleton(){}
    
    public static synchronized ThreadSafeSingleton getInstance(){
        if(instance == null){
            instance = new ThreadSafeSingleton();
        }
        return instance;
    }
    
}

No need to discuss further!

Static objects: To create objects that act like java static methods, you could use Object keyword, or define a companion object in your desired class.

object StaticClass {

    fun callMeLikeAStaticMethod(){

        // logic here...

    }

}

Then, we use it’s methods as static one’s:

class StaticClassUsage {


    fun someOperationsHere(){

        // use it as static
        StaticClass.callMeLikeAStaticMethod()

    }

}

Or, maybe you want some static methods on your ordinary classes, so:

class Foo {
    
    companion object {

        fun someStaticMethod(){

            // logic here
        }

    }

    fun someUsualMethod(){

        // logic here
    }
    
}

And it’s usage:

class StaticClassUsage {

    private val fooInstance = Foo()


    fun SomeCompanionObjectUseCase(){

        // static using companion obejct
        Foo.someStaticMethod()


        // object field
        fooInstance.someUsualMethod()


    }

}

 

Kotlin anonymous class implementation: Another usage of kotlin is to define anonymous classes on-fly.

interface SomeInterface {
    
    fun processString() : String
    fun processNothing()
 
}

We could implement the above interface using Object on-fly like:

fun doSomeOperaion(someInterface: SomeInterface) {
      
      someInterface.processNothing()
      someInterface.processString()
      
  }

class AnonymousObjectUsage {

    private val foo = Foo()

    fun someOperationHere(){
        foo.doSomeOperaion(object : SomeInterface{
            override fun processString(): String {
                // logic here
            }

            override fun processNothing() {
                // logic here
            }

        })
    }

}

 

That’s it, hope you enjoy. feel free to share!.