Search code examples
arrayslistkotlinarraylistdynamic

How to access to the inner ArrayList<Any> binded by an initial ArrayList of type <Any>


I am trying to access to the inner ArrayList in Kotlin... Please refer, herein. Is there a way? Many Thanks

fun main() {
    
    val y = ArrayList<Any>()
    for (i in 1..2){
        y.add(readln().split(' ').map {
            try {
                it.toInt()
            } catch (e: Exception) {
                it
            }
        })
    }
    
    println(y[0]::class.simpleName)
    println(y[1]::class.simpleName)
    println(y)
    y.forEach(::println)
    
}

I printed the class for y[0] and y[1] and the binding class y, all are of type ArrayList. However, accessing to the binding ArrayList is possible by way of lamda expression which shall retrieve the inner ArrayList. The inner list isn't accessible. Is there a way to do it?

Any assistance in this regard is appreciated


Solution

  • Since you fill your list y only with lists, the simplest way to make the inner lists accessible as List would be to provide the type information that y is a list of Lists and not just a list of Anys:

    val y = ArrayList<List<Any>>()
    // now you can also iterate over the inner lists
    y.forEach { it.forEach(::println) }