Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

352
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!