Array Wrapper Looping

I have run into the following a number of times. I have always found a workaround, but I think there is a better (more Kotlin) way to solve it. The situation is when I have a wrapper around an Array. I often have a few functions/variables/constants etc I want to associate with the array, so a wrapper seems like a good way to organize the code. However, I get a message that says I need to implement the Iterator interface and I never succeed so I give up and just expose the Array. I see the Iterator interface, but I can’t figure out how to implement it, let alone know even if I did, would I just run into another problem?

A simple example of a class that wraps a private Array object that I could loop though would be helpful.

Of course, if this is simply not a good idea in Kotlin, that would be good to know too. :slight_smile:

Thank you.

Do you mean something like this?

class MyArray<T>(
    private val arr: Array<T>
) : Iterable<T> {
    override fun iterator() = arr.iterator()
}
1 Like

Yes, that seemed to work. I’m not sure why the compiler kept telling me to implement the Iterator interface. I"ll have to read about Iterable, but it seems to solve the problem.

TY

Depending on the use case, another option would be to just extend the existing array with the functionality you need - e.g.:

fun Array<String>.onlyNumbers() = all { it.matches(Regex("-?\\d+(\\.\\d+)?")) }
...
        when (arrayOf("1", "2", "3").onlyNumbers()) {
            true -> println("only numbers")
            else -> println("mixed")
        }
1 Like