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()
}
}
}