Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
        }
    }
}
like image 636
Stanislas Heili Avatar asked Jan 27 '23 21:01

Stanislas Heili


1 Answers

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
like image 160
Willi Mentzel Avatar answered Feb 06 '23 06:02

Willi Mentzel