7

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()
        }
2
  • 2
    Can't you just return result.toIntArray()? Commented May 18, 2020 at 8:44
  • 3
    This already exists as intersect, (nums1 intersect nums2).toIntArray(). Commented May 18, 2020 at 8:47

2 Answers 2

10

You have an extension function toIntArray()

Example:

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

Or in case of mutableSetOf:

mutableSetOf<Int>(1 ,3 ,4).toIntArray()
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.