How to convert MutableList<Int> to IntArray in Kotlin?

Viewed 1606

I want to convert MutableList to IntArray. I am using toTypedArray() to convert but its resulting in Exception:

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()
                  ^ 

Below is full code :

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()
        }
2 Answers

You have an extension function toIntArray()

Example:

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

Or in case of mutableSetOf:

mutableSetOf<Int>(1 ,3 ,4).toIntArray()
.toTypedArray() for Array<Int>
.toIntArray() for IntArray
Related