Open In App

Singleton Class in Kotlin

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 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 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 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:

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.

Sample Android Program showing Use of Singleton Object:




// 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)
    }
}


Article Tags :