Kotlin generic extension fun

What is the purpose of using generics on extensions?

Like:

fun<T> Call<T>.enqueue(callback: CallBackKt<T>.() -> Unit) {
    val callBackKt = CallBackKt<T>()
    callback.invoke(callBackKt)
    this.enqueue(callBackKt)
}

I know that Call<T> is generic that can be used with any type, like Call<String>, Call<Object>
But what is this generics on fun<T> and CallBackKt<T>.() ?

The actual type (the value of the type parameter) has to come from somewhere and if the function enque wouldn’t be generic the type must have been fixed to some specific type (what is not what you want).

What’s the difference between T and Any?
I think it get the same result

It’s mostly useful if you use T multiple times inside that method or you want to return something with T

If you replace any T with Any you will return likely type Any and then the caller has to cast the result of your method back to the type they want.

For example writing a function like fun <T> List<T>.first() : T = this[0] wouldn’t really work with Any.

You could write fun List<Any>.first() : Any = this[0] but then you can’t really use the result without casting it back to String or Int or whatever your list is typed at.

3 Likes