Table of contents |
|
Singleton Class in Kotlin |
|
Singleton Object and Companion Objects |
|
Understanding Singleton Objects in Kotlin |
|
Sample Android Program Demonstrating Singleton Object Usage |
|
Singleton Class in Kotlin, also known as the Singleton Object, ensures that only one instance of the class can be created and utilized universally. Repeatedly creating multiple objects of the same class results in the allocation of separate memory spaces for each object. Hence, it is more efficient to instantiate a single object and reuse it.
// Kotlin program
fun main(args: Array)
{
val obj1 = GFG()
val obj2 = GFG()
println(obj1.toString())
println(obj2.toString())
}
class
GFG
Output:
In the above example, both objects have distinct addresses, resulting in memory wastage. In the subsequent program, we employ a singleton class to address this issue.
println(GFG.toString())
// GFG is the singleton class here
object GFG
By utilizing an object instead of a class, Kotlin automatically applies the Singleton pattern, efficiently allocating a single memory space. In Java, a singleton class is created by defining a class named Singleton, whereas in Kotlin, the 'object' keyword is used. The 'object' class can comprise functions, properties, and the 'init' method, but it does not allow a constructor. If initialization is required, the 'init' method can be utilized, and the 'object' can be nested inside a class. Methods and member variables within the singleton class are accessed using the class name, akin to companion objects.
fun main(args: Array)
println(GFG.name)
println("The answer of addition is ${GFG.add(3,2)}")
println("The answer of addition is ${GFG.add(10,15)}")
// 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 |