NeeK
NeeK

Reputation: 902

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

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<Int> 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()
        }

Upvotes: 7

Views: 4248

Answers (2)

Fortran
Fortran

Reputation: 2336

.toTypedArray() for Array<Int>
.toIntArray() for IntArray

Upvotes: 1

apksherlock
apksherlock

Reputation: 8371

You have an extension function toIntArray()

Example:

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

Or in case of mutableSetOf:

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

Upvotes: 10

Related Questions