Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java for Android
  • Android Studio
  • Android Kotlin
  • Kotlin
  • Flutter
  • Dart
  • Android Project
  • Android Interview
Open In App
Next Article:
Singleton Class in Kotlin
Next article icon

Singleton Class in Kotlin

Last Updated : 14 Sep, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

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

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

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

Next Article
Singleton Class in Kotlin

L

lavishgarg26
Improve
Article Tags :
  • Kotlin
  • Android

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences