Kotlin在逆变类型上的星形投影 [英] Kotlin star projection on contravariant types

查看:184
本文介绍了Kotlin在逆变类型上的星形投影的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读并试图了解Kotlin类型的投影,有时我会提出令人困惑的事情:



逆变类型具有星形投影的意义是什么,它是如何产生的?

解决方案

也在Kotlin 文档中进行了解释:


对于 Foo<在T> 中,其中 T 逆变类型型参数, Foo 相当于 Foo in Nothing> 。这意味着当 T Foo <*>



示例



我们有一个类 Foo< T> 与逆变 T (声明站点),即 Foo 只能作为 T 的消费者:

  class Foo< ;在T> {
fun accept(t:T){
println(t)
}
}

我们可以在简单泛型函数中使用这种类型,如下所示:

  fun< F> ; usingFoo(con:Foo< F>,t:F){
con.accept(t)
}

(用于 F 为了与类类型参数 T >区分开)



这样做很好,因为我们使用 Foo 作为预期:作为 T $ b $现在,你的引用只是说有一个类型的参数:Foo<> 代替 con:Foo< T> 会产生以下效果:你不能调用任何具有 T 签名



因此,以下操作将失败:

  fun< F> usingFoo(con:Foo *,t:F){
con.accept(t)//不允许!

调用 accept F ,因为我们不知道 Foo 的类型(用明星投影)。


星际投影:有时候你想说你一无所知类型参数,但仍想以安全的方式使用它。这里的安全方法是定义这样一个泛型类型的投影,那个泛型的每个具体实例都是该投影的子类型。



I am reading and trying to understand Kotlin type projections, sometimes I come up with confusing things like this:

What does it mean to contravariant type to have a star projection and how does it come up to

解决方案

This is also explained in the Kotlin documentation:

For Foo<in T>, where T is a contravariant type parameter, Foo<*> is equivalent to Foo<in Nothing>. It means there is nothing you can write to Foo<*> in a safe way when T is unknown.

Example

We have a class Foo<T> with contravariant T (declaration-site), i.e. Foo only works as a consumer of T:

class Foo<in T> {
    fun accept(t: T) {
        println(t)
    }
}

We can use this type in simple generic functions as follows:

fun <F> usingFoo(con: Foo<F>, t: F) {
    con.accept(t)
}

(used F in order to distinguish from class type parameter T)

This works fine since we use Foo as intended: As a consumer of Ts.

Now, your quote simply says that having a parameter of type con: Foo<*> instead of con: Foo<T> would have the following effect: "you can't call any methods that have T in the signature".

Thus, the following fails:

fun <F> usingFoo(con: Foo<*>, t: F) {
    con.accept(t) //not allowed!!
}

It's not safe to call accept with an instance of F because we don't know the type of Foo (denoted by star projection).

Star Projection: Sometimes you want to say that you know nothing about the type argument, but still want to use it in a safe way. The safe way here is to define such a projection of the generic type, that every concrete instantiation of that generic type would be a subtype of that projection.

这篇关于Kotlin在逆变类型上的星形投影的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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