Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

283
Vistas
Why use companion object to make singleton in Kotlin?

I'm studying creation pattern(Singleton pattern) in android kotlin.

I have question about difference in making singleton object by companion object and object.

In some example, singletons are made like this.

class ABC {
  companion object {
    private var sInstance: ABC? = null
    
    fun getInstance(): ABC {
        if (sInstance == null) sInstance = ABC()
        return sInstance ?: throw IllegalStateException("")
    }
  }
}

but with above method,

// a and b are not same object
val a = ABC()
val b = ABC.getInstance()

println(a == b) // false

but what I know, singleton in kotlin is just object.

So, my question is "Why, When use companion object to make singleton object"

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

getInstance() is just a "traditional" way of creating singletons. It is a common technique in e.g. Java, because contrary to Kotlin, Java doesn't have singletons provided by the language itself. For this reason you will see getInstance() from time to time in Kotlin as well. It may be the code ported from Java, it may be developed by a person who has more experience with Java, so they don't know there is a better alternative in Kotlin, etc.

Additionally, object is pretty much static. If we have more complicated logic for creating a singleton, it may be required to create it by some kind of factory (e.g. companion object).

So I would say, the rule of thumb is to use object as a default and only if this is not possible, create it manually. And in the latter case, it is more "Kotlin-ish" to use a property, not a getInstance() function.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda