如何在Kotlin中将MutableList <Int>转换为IntArray?

我想将MutableList转换为IntArray。我正在使用toTypedArray()进行转换,但导致异常:

Line 15: Char 23: error: type inference failed. Expected type mismatch: inferred type is Array&lt;Int&gt; but IntArray was expected
        return result.toTypedArray()
                  ^ 

下面是完整的代码:

fun intersection(nums1: IntArray, nums2: IntArray): IntArray {
            val set: MutableSet<Int> = mutableSetOf()
            val result: MutableList<Int> = mutableListOf()

            for(num in nums1) set.add(num)

            for(num in nums2) {
                if(set.contains(num)) {
                    result.add(num)
                    set.remove(num)
                }
            }

            return result.toTypedArray()
        }
评论
  • Laura
    Laura 回复

    You have an extension function toIntArray()

    例:

    mutableListOf<Int>(1, 3, 4).toIntArray()
    

    Or in case of mutableSetOf:

    mutableSetOf<Int>(1 ,3 ,4).toIntArray()