What is the usage of the <T>
type parameter before the function name in Kotlin?
Example:
fun <T> MutableList<T>.swap(index1: Int, index2: Int) {
val tmp = this[index1]
this[index1] = this[index2]
this[index2] = tmp
}
Referring to the first <T>
above.
I've tried to look through the Kotlin docs regarding generics as well as the Java Generics however they mostly just touch on the 2nd <T>
not the first.
It is used to indicate that generics are used and not some type T
is referenced.
Have a look at this completly valid example
fun <String> MutableList<String>.swap(index1: Int, index2: Int)
Now this can be called on any MutableList<*>
and not only MutableList<String>
. If you would not write <String>
after the fun
keyword, how would kotlin know that in fact you were referencing a generic and not kotlin.String
?
The same goes for the example you've shown. The <>
after the fun
just introduces a new generic parameter, else kotlin would complain that it wouldn't know the type T