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

Nee*_*eeK 5 kotlin

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

Line 15: Char 23: error: type inference failed. Expected type mismatch: inferred type is Array<Int> but IntArray was expected
        return result.toTypedArray()
                  ^ 
Run Code Online (Sandbox Code Playgroud)

以下是完整代码:

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()
        }
Run Code Online (Sandbox Code Playgroud)

cor*_*her 8

你有一个扩展功能toIntArray()

例子:

mutableListOf<Int>(1, 3, 4).toIntArray()
Run Code Online (Sandbox Code Playgroud)

或者如果出现以下情况mutableSetOf

mutableSetOf<Int>(1 ,3 ,4).toIntArray()
Run Code Online (Sandbox Code Playgroud)