Singleton Class in Kotlin
Last Updated : 14 Sep, 2020
Singleton Class in Kotlin is also called as the Singleton Object in Kotlin. Singleton class is a class that is defined in such a way that only one instance of the class can be created and used everywhere. Many times we create the two different objects of the same class, but we have to remember that creating two different objects also requires the allocation of two different memories for the objects. So it is better to make a single object and use it again and again.
Kotlin // Kotlin program fun main(args: Array<String>) { val obj1 = GFG() val obj2 = GFG() println(obj1.toString()) println(obj2.toString()) } class GFG { }
Output:
In the above example, we can see that both the objects have a different address, thus it is a wastage of memory. In the below program, we have done the same thing, but we have used the singleton class.
Kotlin // Kotlin program fun main(args: Array<String>) { println(GFG.toString()) println(GFG.toString()) } // GFG is the singleton class here object GFG { }
Output:
So when we use an object instead of a class, Kotlin actually uses the Singelton and allocates the single memory. In Java, a singleton class is made making a class named Singleton. But in Kotlin, we need to use the object keyword. The object class can have functions, properties, and the init method. The constructor method is not allowed in an object so we can use the init method if some initialization is required and the object can be defined inside a class. We call the method and member variables present in the singleton class using the class name, as we did in the companion objects.
Kotlin // Kotlin program fun main(args: Array<String>) { println(GFG.name) println("The answer of addition is ${GFG.add(3,2)}") println("The answer of addition is ${GFG.add(10,15)}") } object GFG { init { println("Singleton class invoked.") } var name = "GFG Is Best" fun add(num1:Int,num2:Int):Int { return num1.plus(num2) } }
Output:

Properties of Singleton Class
The following are the properties of a typical singleton class:
- Only one instance: The singleton class has only one instance and this is done by providing an instance of the class, within the class.
- Globally accessible: The instance of the singleton class should be globally accessible so that each class can use it.
- Constructor not allowed: We can use the init method to initialize our member variables.
Importance of Singleton Objects In Android
Below are some points which explain the importance of singleton objects in android along with some examples, where it must be used, and reasons for why android developers should learn about singleton objects.
- As we know that when we want a single instance of a particular object for the entire application, then we use Singleton. Common use-cases when you use the singleton is when you use Retrofit for every single request that you make throughout the app, in that case, you only need the single instance of the retrofit, as that instance of the retrofit contains some properties attached to it, like Gson Converter(which is used for conversion of JSON response to Java Objects) and Moshy Converter, so you want to reuse that instance and creating a new instance again and again would be a waste of space and time, so in this case, we have to use singleton objects.
- Consider the case when you are working with the repository in MVVM architecture, so in that case, you should only create only 1 instance of the repository, as repositories are not going to change, and creating different instances would result in space increment and time wastage.
- Suppose you have an app, and users can Login to it after undergoing user authentication, so if at the same time two user with same name and password tries to Login to the account, the app should not permit as due to concern of security issues. So singleton objects help us here to create only one instance of the object, i.e user here so that multiple logins can't be possible. Hope these examples are sufficient to satisfy the reader to explore more about singleton objects in Kotlin so that they can use singleton object in their android projects.
Sample Android Program showing Use of Singleton Object:
Kotlin // sample android application program in kotlin // showing use of singleton object package com.example.retrofitexample import retrofit2.Call import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.GET import retrofit2.http.Query const val BASE_URL = "https://newsapi.org/" const val API_KEY = "ff30357667f94aca9793cc35b9e447c1" interface NewsInterface { @GET("v2/top-headlines?apiKey=$API_KEY") fun getheadlines(@Query("country")country:String,@Query("page")page:Int):Call<News> // function used to get the headlines of the country according to the query // written by developer } // NewsService is the instance of retrofit made by using Singleton object object NewsService { val newsInstance:NewsInterface init { val retrofit=Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() newsInstance=retrofit.create(NewsInterface::class.java) } }
Similar Reads
Singleton Class in Android The Singleton Pattern is a software design pattern that restricts the instantiation of a class to just "one" instance. It is used in Android Applications when an item needs to be created just once and used across the board. The main reason for this is that repeatedly creating these objects, uses up
4 min read
Kotlin Sealed Classes Kotlin introduces a powerful concept that doesn't exist in Java: sealed classes. In Kotlin, sealed classes are used when you know in advance that a value can only have one of a limited set of types. They let you create a restricted class hierarchy, meaning all the possible subclasses are known at co
4 min read
How to Get the Class in Kotlin? Kotlin is a statically typed, general-purpose programming language developed by JetBrains, that has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc. It was first introduced by JetBrains in 2011 and is a new language for the JVM. Kotlin is an object-oriented language, and a âbetter
3 min read
Kotlin Inline classes Inline classes are introduced by Kotlin since Kotlin 1.3 version to overcome the shortcomings of traditional wrappers around some types.These Inline classes add the goodness of Typealiases with the value range of the primitive data types. Let us suppose that we are selling some items and the cost is
4 min read
Kotlin Nested class and Inner class In Kotlin, you can define a class inside another class. Such classes are categorized as either nested classes or inner classes, each with different behavior and access rules.Nested ClassA nested class is a class declared inside another class without the inner keyword. By default, a nested class does
3 min read