T和T有什么区别?在科特林? [英] What's the difference between T and T? in Kotlin?

查看:66
本文介绍了T和T有什么区别?在科特林?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之间有什么区别

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,因此:TT?之间是否有区别?

In my test, null is accepted for all 3 transform functions above, so: Is there any difference between T and T??

推荐答案

在您的示例中,TT?是等效的,但是在其他情况下?确实会有所作为.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆