Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Kotlin 2D Array of Strings Inference Type Error Using indexOf

I am trying to use a set 2D array to pull data. I am trying to find the Index of a String object in an array, and use that Index to pull data from the same row but separate column so I don’t have a massive chain of 16 if loops for every single piece of math I need.

Here is the code snippet.

@Composable
    fun TimeCalculation(
        songVar: String, // songVar is a string that changes from another composable
        arrayOfSongs: kotlin.Array<kotlin.Array<String>>
    ) {
        if (songVar != "") {
            val index = arrayOfSongs.indexOf(songVar) // <-- Error on 'indexOf'
        } else {
            var time1 = 0.0
        }

arrayOfSongs is initialized above as follows:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

val arrayOfSongs = rememberSaveable { // no errors here
    arrayOf(
        arrayOf("songTitle1", "3.46"),
        arrayOf("songTitle2", "4.22"),
// more code for a longer array follows

And I am sending the array to the Composable as follows:

TimeCalculation(
    songVar, arrayOfSongs) // no errors here

Originally, I had declared the arrayOfSongs array inside the composable, but was met with the same error.

>Solution :

The error message shown by the IDE is slightly confusing:

Type inference failed. The value of the type parameter T should be mentioned in input types (argument types, receiver type or expected type). Try to specify it explicitly.

The actual issue is that there’s a type mismatch between the elements of arrayOfSongs and the argument you’re passing to indexOf(). Each element in arrayOfSongs is an array, but you’re trying to pass a simple String.

If you’re looking for the index of the first sub-array that starts with songVar, try something like this:

val index = arrayOfSongs.indexOfFirst { it[0] == songVar }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading