Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a generic extension method in Kotlin?

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?

like image 239
AdamMc331 Avatar asked Dec 07 '22 18:12

AdamMc331


2 Answers

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
}
like image 126
JB Nizet Avatar answered Dec 10 '22 09:12

JB Nizet


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
}
like image 32
Mibac Avatar answered Dec 10 '22 09:12

Mibac