In a project I'm working on, I've found myself writing a few extension methods for some types to return a default value if an optional is null.
For example, I may have a Boolean?
object, and I want to use it in a conditional expression defaulted to false, so I would write:
if (myOptional?.default(false)) { .. }
I've written this for a few types:
fun Boolean?.default(default: Boolean): Boolean {
return this ?: default
}
fun Long?.default(default: Long): Long {
return this ?: default
}
fun Int?.default(default: Int): Int {
return this ?: default
}
I'm wondering if there's a way to do this generically, so I can write one extension method that I can use for all types?
I would not do that, and use the standard ?:
operator that every Kotlin developer should know, and that is more concise.
But to answer your question:
fun main(args: Array<String>) {
val k1: Long? = null
val k2: Long? = 4L
println(k1.default(0L)) // prints 0
println(k2.default(0L)) // prints 4
}
fun <T> T?.default(default: T): T {
return this ?: default
}
You can create a method to do this and it's below though I don't get why would you want a method for that? You can basically just use ?:
directly. It's both more readable and compact.
Extension function:
fun <T> T?.default(default: T): T {
return this ?: default
}
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