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

354
Vistas
Does Kotlin support Optional Constructors like swift?

I would like to use in Kotlin an optional constructor that either creates an object or returns null.

Here is a Swift example to show how I would like it to work:

class Beer {
    init?(yourAge : Int){
        if yourAge < 21 {
            return nil
        }
    }
}
Beer(yourAge: 17) //is nil
Beer(yourAge: 23) //a Beer object

I could of course put the check in another function (below is a Kotlin equivalent of the previous example), but it is not as nice

class Beer(){
    fun initialize(yourAge : Int): Beer? {
        if (yourAge < 21){
            return null
        }else {
            return Beer()
        }
    }
}
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Kotlin does not support optional constructors as Yole already said, but you can achieve exactly what you want with an invoke operator defined inside a companion object:

class Beer {
    companion object {
        operator fun invoke(yourAge: Int) = if (yourAge < 21) {
            null
        } else {
            Beer()
        }
    }
}

Beer(17) // null
Beer(23) // instance of Beer
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