kotlinindexofdata-classlistof

how do I use IndexOf with an object Array of a data class?


fun main() {
    data class seriesData( 
        var seriesName: String = "",
        var bookListEntries: MutableList<Int> = arrayListOf() {}
    var mySeriesData: MutableList<seriesData> = ArrayList()
    for (i in 0..5) {
        var myString: String = "series" + i.toString() 
        mySeriesData.add(seriesData(seriesName = myString, 
                                    bookListEntries = ArrayList()))
    }
    // I want to find an occurrence of one of the strings
    println(mySeriesData.seriesName.indexOf("series2")) 
    // The last statement always gives me unresolved reference on seriesName
}

I have tried several variations of the above including putting the two variables in the body of the data class with a dummy key and using "it." with no success. I am new to Kotlin. I know some of the above code can be streamlined, but I broke it out to help clarify the steps.


Solution

  • This indexOf function is gives you entire data class not a single value under the data class

    For example

    If you have below data class

    data class seriesData(
        var seriesName: String = "",
        var bookListEntries: MutableList<Int> = arrayListOf(),
    )
    

    And you run the loop on this data class for fill the value of variables under the data class

    val mySeriesData: MutableList<seriesData> = ArrayList()
    
    for (i in 0 .. 5) {
        var myString: String = "series" + i.toString()
        mySeriesData.add(
            seriesData(
                seriesName = myString,
                bookListEntries = ArrayList()
            )
        )
    }
    

    And now you wants to know that which is the index of "series2" value

    Then you need a entire data class for that

    in the indexOf function you need to pass entire data class like this :

    mySeriesData.indexOf(seriesData("series3", ArrayList()))