簡體   English   中英

將 java 泛型轉換為 kotlin 后出現類型不匹配錯誤

[英]Type mismatch error after converting java generic to kotlin

轉換為kotlin后出現如下錯誤: 類型不匹配錯誤

java 代碼。 沒有錯誤:

public class Test {

    public void getList() {
        List<Parent> list = join(
                Parent.Child1.values(),
                Parent.Child2.values()
        );
    }
    public interface Parent {
        enum Child1 implements Parent {}
        enum Child2 implements Parent {}
    }
    public <T> List<T> join(T[]... collections) {
        ArrayList<T> result = new ArrayList<>();
        for (T[] collection : collections) {
            result.addAll(Arrays.asList(collection));
        }
        return result;
    }
}

kotlin 代碼。 類型不匹配錯誤

class Test2 {
    val list: Unit
        get() {
            val list = join<Parent>(
                Parent.Child1.values(),
                Parent.Child2.values()
            )
        }

    interface Parent {
        enum class Child1 : Parent
        enum class Child2 : Parent
    }

    fun <T> join(vararg collections: Array<T>): List<T> {
        val result = ArrayList<T>()
        for (collection in collections) {
            result.addAll(collection.toList())
        }
        return result
    }
}

請幫助我,我該如何解決這個錯誤?

不知道如何解決

我相信這是 Java 數組類型實現設計中的一個弱點,它允許您這樣做。 它保留了將T (在本例中為父級)放入只能接受T的某些子類型的數組的可能性,這將在運行時拋出異常。

Kotlin 比 generics 更嚴格,防止可能因您可能做出的任何意外假設而導致運行時崩潰。 Java arrays 不要使用 generics 開頭。

將 function 參數的類型更改為Array<out T> 這意味着它是一個數組,您可以從中提取Parent ,但編譯器會阻止您將 Parent 的任意子類型放入其中(它是 Parent 生產者,但不是消費者)。 這意味着Child1Child2數組是僅生成的 Parents 數組的有效子類型。

fun <T> join(vararg collections: Array<out T>): List<T> {
    //...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM