通用类型< T>函数名称前的参数 [英] Generic type <T> parameter BEFORE the function name
问题描述
在Kotlin中,函数名称前<T>
类型参数 的用途是什么?
What is the usage of the <T>
type parameter before the function name in Kotlin?
示例:
fun <T> MutableList<T>.swap(index1: Int, index2: Int) {
val tmp = this[index1]
this[index1] = this[index2]
this[index2] = tmp
}
请参阅上面的第一个<T>
.
我尝试浏览 Kotlin文档关于泛型以及 Java泛型,但是它们大多只是触及第二个<T>
而不是第一个.
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.
推荐答案
它用于指示已使用泛型,但未引用某些类型的T
.
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)
现在可以在任何MutableList<*>
上调用它,而不仅仅是MutableList<String>
.如果您不愿意在fun
关键字后写<String>
,那么kotlin怎么会知道您实际上是在引用泛型而不是kotlin.String
?
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
?
您所显示的示例也是如此. fun
之后的<>
只是引入了一个新的通用参数,否则kotlin会抱怨它不知道类型T
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
这篇关于通用类型< T>函数名称前的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!