T和T有什么区别?在科特林? [英] What's the difference between T and T? in Kotlin?
问题描述
之间有什么区别
fun <T, R> List<T>.map1(transform: (T) -> R): List<R> {
return this.map(transform)
}
和
fun <T, R> List<T>.map2(transform: (T?) -> R): List<R> {
return this.map(transform)
}
和
fun <T, R> List<T?>.map3(transform: (T?) -> R): List<R> {
return this.map(transform)
}
在我的测试中, 以上所有3个转换函数 均接受null
,因此:T
和T?
之间是否有区别?>
In my test, null
is accepted for all 3 transform functions above, so: Is there any difference between T
and T?
?
推荐答案
在您的示例中,T
和T?
是等效的,但是在其他情况下?
确实会有所作为.
In your examples, T
and T?
are equivalent, but there are other cases where the ?
does make a difference.
声明类型参数<T>
时,对其没有任何限制.这与编写<T: Any?>
相同,这意味着T
将允许Any?
的任何子类型.向其中添加?
将使其可为空,但是Any?
已经为可为空,因此?
不会更改任何内容.这意味着 unbounded 类型T
所允许的类型集与T?
所允许的类型集相同.
When you declare a type parameter <T>
, it doesn't have any restrictions on it. It's the same as writing <T: Any?>
, and it means T
will allow any sub-type of Any?
. Adding a ?
to it would make it nullable, but Any?
is already nullable, so the ?
doesn't change anything. That means that the set of types allowed by an unbounded type T
is the same as the set of types allowed by T?
.
一旦对T
进行限制,情况就会发生变化.例如,在以下函数中,我们声明类型参数<T: Any>
,对其进行限制,以使其不再可为空.
As soon as you put restrictions on what T
can be, things change, though. For example, in the following function, we declare a type parameter <T: Any>
, restricting it so it's no longer nullable.
fun <T: Any> myFunction(item: T) // item can't be null
这意味着我无法将null
传递给myFunction
.如果将参数的类型更改为T?
,则只能使用null
参数调用该函数.
That means I can't pass null
to myFunction
. I can only call the function with a null
argument if I change the type of the parameter to be T?
.
fun <T: Any> myFunction(item: T?) // item can be null
请注意,?
只是注释现有的类型参数.用?
声明 类型参数并不意味着什么,也不会编译.例如,fun <T?> myFunction(item: T)
不是有效的Kotlin代码.
Note that the ?
just annotates an existing type parameter. Declaring a type parameter with a ?
doesn't mean anything and doesn't compile. For example, fun <T?> myFunction(item: T)
isn't valid Kotlin code.
这篇关于T和T有什么区别?在科特林?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!