AdamMc331
AdamMc331

Reputation: 16730

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?

Upvotes: 4

Views: 4159

Answers (2)

Mibac
Mibac

Reputation: 9488

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
}

Upvotes: 3

JB Nizet
JB Nizet

Reputation: 692181

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
}

Upvotes: 12

Related Questions