Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Kotlin:返回数组<;E>;来自返回类型为数组的函数<;I>;如果E是实现接口I的枚举类_Kotlin_Enums_Type Mismatch_Generic Variance - Fatal编程技术网

Kotlin:返回数组<;E>;来自返回类型为数组的函数<;I>;如果E是实现接口I的枚举类

Kotlin:返回数组<;E>;来自返回类型为数组的函数<;I>;如果E是实现接口I的枚举类,kotlin,enums,type-mismatch,generic-variance,Kotlin,Enums,Type Mismatch,Generic Variance,最近,我遇到了一个问题,我有一个函数,它必须返回一个Is数组,以enumE的所有值的形式,用E实现接口I,我想到的每一个代码编译器都抱怨类型不匹配: Error:(x, x) Kotlin: Type mismatch: inferred type is Array<E> but Array<I> was expected 我在这个主题上做了很多搜索,但是没有运气(也许我选择了错误的方式来描述它?在Kotlin,与Java不同,数组在T上是不变的,因此,对于E这是I的一

最近,我遇到了一个问题,我有一个函数,它必须返回一个
I
s数组,以enum
E
的所有值的形式,用
E
实现接口
I
,我想到的每一个代码编译器都抱怨类型不匹配:

Error:(x, x) Kotlin: Type mismatch: inferred type is Array<E> but Array<I> was expected

我在这个主题上做了很多搜索,但是没有运气(也许我选择了错误的方式来描述它?

在Kotlin,与Java不同,
数组
T
上是不变的,因此,对于
E
这是
I
的一个子类型,
数组
数组
不是彼此的子类型。请参阅:

考虑到
数组
类型也存储项目类型,并且不能完全受约束,解决此问题的最佳方法是创建一个单独的数组

您可以通过手动创建一个数组并用项填充它来实现这一点,如在您的示例中(或通过使用构造函数),或者使用应用于数组的列表表示形式():

fun getMoreInterfaces():数组{
返回E.values().asList().toTypedArray()
}

但基本上,如果您没有使用性能关键型代码,您可以使用
列表
,这对于Kotlin来说比使用数组更为惯用,也更简单


另请参见:

Array
在Kotlin中是一个不变的泛型类型,因此如果需要返回
Array
的实例,则不能返回
Array
,即使
E
I
的子类型

但如果您仅使用返回数组中的值,则可以将其类型声明为
数组
。此类型是
Array
类型的协变投影,它允许您同时返回
Array
Array

接口I{}
枚举E类:I类{
A、 B,C
}
有趣的getMoreInterfaces():数组{
返回E.values()
}
    interface I {}
    enum class E: I {
        A, B, C;
    }
    fun getMoreInterfaces(): Array<I> {
        return E.values()
    }
    interface I {}
    enum class E: I {
        A, B, C;
    }
    fun getMoreInterfaces(): Array<I> {
        return arrayOf(E.A, E.B, E.C)
    }
fun getMoreInterfaces(): Array<I> {
    return E.values().asList().toTypedArray()
}
interface I {}
enum class E: I {
    A, B, C
}
fun getMoreInterfaces(): Array<out I> {
    return E.values()
}