Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

353
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda