How to write a generic extension method in Kotlin?
extension-methods, generics, kotlin
Solution
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
}
Problem
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?