协变类型T发生在相反位置 [英] covariant type T occurs in contravariant position

查看:68
本文介绍了协变类型T发生在相反位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道之前曾有人问过这个问题,但是要么答案不适用于这种情况,要么我不理解。

I know this question has been asked before, but either the answers don't apply to this case, or I don't understand them.

基本上,为什么不以下(重新创建我的问题的简单示例)工作?

Basically, why doesn't the following (simple example that recreates my problem) work ?

class Test[+T] {
    var list: List[T] = _
}

我遇到的问题是我有一个对象,我想在其中传递 Test [Nothing] (空的 Test )的实例,除非我使 T 中的$ c> Test 协变量。

The problem I am having is that I have an object, where I want to pass in an instance of Test[Nothing] (the empty Test), and this doesn't work unless I make Test co-variant in T.

推荐答案

T 中进行检验协变量意味着 Test [A] 是<$ c $的子类型c> Test [Any] 中的任何 A 。因此,让我们创建一个 Test

Making test covariant in T means that Test[A] is a subtype of Test[Any] for any A. So lets create a Test:

val test_string = new Test[String]

现在我们有一个 Test [String] ,并且包含的​​列表的类型为 List [String]

Now we have a Test[String] and the contained list is type List[String].

由于 Test [String] Test [Any] 的子类型,因此应允许以下内容:

Since Test[String] is a subtype of Test[Any], the following should be allowed:

val test_any : Test[Any] = test_string

现在,我们有一个 Test [Any] ,因此 test_any.list 的类型为 List [Any] ,这意味着以下内容应有效:

And now, we have a Test[Any], and therefore test_any.list is type List[Any], which means the following should be valid:

test_any.list = List[Any]()

这意味着我们刚刚分配了一个 List [Any] 到test_strings列表成员,不应该被允许,因为这应该是 List [String] ,而不是 List [Any] 。这也意味着您可以在列表之前添加任何内容,因为它是 List [Any] 的类型。

Which means we just assigned a List[Any] to test_strings list member, which shouldn't be allowed, since that is supposed to be a List[String], not a List[Any]. It also means you could prepend anything at all to the list, since it is type List[Any].

这篇关于协变类型T发生在相反位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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