Software Development Exam  >  Software Development Notes  >  Singleton Class in Kotlin

Singleton Class in Kotlin - Software Development PDF Download

Singleton Class in Kotlin

Last Updated : 14 Sep, 2020

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
// Kotlin program fun main(args: Array) { val obj1 = GFG() val obj2 = GFG() println(obj1.toString()) println(obj2.toString()) } class GFG { } // Kotlin program fun main(args: Array) { val obj1 = GFG() val obj2 = GFG() println(obj1.toString()) println(obj2.toString()) } classGFG

Output:

Singleton Class in Kotlin - Software Development

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.

// Kotlin program fun main(args: Array) { println(GFG.toString()) println(GFG.toString()) } // GFG is the singleton class here object GFG { } println(GFG.toString()) // GFG is the singleton class here object GFG Singleton Class in Kotlin - Software Development

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.

Singleton Object and Companion Objects

  • A singleton object in Kotlin is an object that is declared using the "object" keyword and can have properties and methods.
  • Companion objects are similar to static methods in Java and are declared using the "companion object" keyword.
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)}")

Output:

Singleton Class in Kotlin - Software Development

Properties of Singleton Class

  • Only one instance: The singleton class has only one instance, ensuring there is a unique object of that class.
  • Globally accessible: The instance of the singleton class is accessible globally, allowing all classes to use it as needed.
  • Constructor not allowed: Instead of a constructor, the init method is used to initialize member variables of the singleton class.
  • Singleton Class Characteristics:
    • The singleton class is designed to have only one instance, achieved by embedding an instance of the class within the class itself.
    • The instance of the singleton class must be globally accessible, allowing all classes to utilize it.
    • Unlike regular classes, a constructor is not permitted in a singleton class. Initialization of member variables is usually done through an init method.
  • Importance of Singleton Objects In Android:
    • Singleton objects play a crucial role in Android development by ensuring that only one instance of a particular object exists throughout the entire application.
    • Examples of the significance of singleton objects in Android include:
    • Use Case 1 - Retrofit in Network Requests:
      • When utilizing Retrofit for network requests in an app, it is essential to have a single instance of Retrofit. This single instance contains properties like Gson Converter and Moshy Converter, which should be reused to prevent unnecessary resource consumption and time delays.
    • Use Case 2 - Repository in MVVM Architecture:
      • In the MVVM architecture, repositories remain constant. Therefore, creating only one instance of the repository is advisable to avoid redundant memory usage and processing time.
    • Use Case 3 - User Authentication:
      • Singleton objects are beneficial in scenarios such as user authentication. For instance, in an app where multiple logins with the same credentials should be restricted for security reasons, a singleton object can ensure that only one instance of the user object exists.

Understanding Singleton Objects in Kotlin

  • Singleton objects are utilized in situations where a single instance of an object is needed across an entire application. They are crucial for conserving resources and time by avoiding the creation of multiple instances.
  • One common scenario where singletons are employed is when using Retrofit in Android development. Retrofit instances, which contain properties like Gson Converter and Moshy Converter, should be singular to ensure efficient reuse.
  • In the context of MVVM architecture, repositories are typically kept as single instances to prevent unnecessary resource consumption and time wastage.
  • Singleton objects play a vital role in maintaining security and integrity in applications. For instance, in a user authentication system, a singleton object can ensure that only one instance of a user is active at a time, preventing security vulnerabilities that may arise from multiple logins under the same credentials.
  • Sample Android Program Demonstrating Singleton Object Usage

  • In the provided Kotlin program, a singleton object named NewsService is created to handle API calls using Retrofit, showcasing the practical implementation of a singleton pattern within an Android application.
  • Please Login to comment...

    LoginLike
    // 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 // 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) } }
    The document Singleton Class in Kotlin - Software Development is a part of Software Development category.
    All you need of Software Development at this link: Software Development
    Download as PDF

    Top Courses for Software Development

    Related Searches

    shortcuts and tricks

    ,

    Important questions

    ,

    Free

    ,

    practice quizzes

    ,

    Sample Paper

    ,

    Singleton Class in Kotlin - Software Development

    ,

    Singleton Class in Kotlin - Software Development

    ,

    Extra Questions

    ,

    Singleton Class in Kotlin - Software Development

    ,

    study material

    ,

    MCQs

    ,

    Summary

    ,

    Objective type Questions

    ,

    pdf

    ,

    mock tests for examination

    ,

    Semester Notes

    ,

    past year papers

    ,

    Previous Year Questions with Solutions

    ,

    Viva Questions

    ,

    video lectures

    ,

    ppt

    ,

    Exam

    ;