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()
}
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With