0

This may be a dumb question, but I have an array:

var testarray = arrayOf(0,0,arrayOf(7,5,2))

So I tried to access the second array by typing testarray[2][1]. However, this throws an error:

error: unresolved reference. None of the following candidates is applicable because of receiver type mismatch: 
@InlineOnly public inline operator fun <@OnlyInputTypes K, V> Map<out Int, ???>.get(key: Int): ??? defined in kotlin.collections
testarray[2][1]
^
error: no get method providing array access
testarray[2][1]

Is there a way to access the nested array?

2 Answers 2

3

Your outer array contains Ints, and an array. So its actual declared type (that you could specify, or could let the IDE specify for you), is Array<Serializable>.

A Serializable could be anything. The compiler doesn't know that the element at index 2 happens to be an array. So it can't let you use the [] operator on it. You need to cast the element to an array to be able to do that:

println((testarray[2] as Array<Int>)[1])

That would fix the compilation issue, but not the design issue. Using arrays in general is already a smell, but using arrays containing mixed types is an even bigger smell. You should reconsider your design.

Sign up to request clarification or add additional context in comments.

3 Comments

So use MutableLists instead in this case? Or would there be a better datatype in this case?
I don't know enough about your use-case to recommend anything concrete. In general you should favor collections over arrays, and immutable collections over mutable ones.
I need to be able to modify the values inside the object, but I do not need to change the length.
1

I also think that you should rethink your design as JB Nizet already said.

You could do that by generalizing your array to an array of arrays like this:

val testArray = arrayOf(arrayOf(0), arrayOf(0), arrayOf(7, 5, 2))

which would ensure that you can get and set elements like this:

testArray[2][1]
testArray[2][0] = 4

As long as you just want to access the elements in the fashion you described keeping your design you could create a (local) operator extension function get on Serializable like this:

operator fun Serializable.get(i: Int) = (this as? Array<*>)?.get(i) ?: this

val a = arrayOf(0, 0, arrayOf(7,5,2))

println(a[1][0]) // 0
println(a[2][1]) // 5

2 Comments

That's definitely feasible. Actually I like this idea the more I think about it. If it's a 2d array, I should have to pass the array element anyway.
I'm getting 'error: no set method providing array access' whenever I try to change the values in the array

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.