kotlinandroid-studiocollectionsruntime-error

Update from compileSdk 34 to 35 causes java.util.List java.util.List.reversed() to not be found at runtime


I have a library project in Kotlin compiled in Android Studio, I try to keep it up to date with latest changes whenever a small code adjustment is made.

I recently made a small adjustment and the IDE suggested updating from targetSdkVersion 34 to targetSdkVersion 35

When I do this it compiles fine but I receive runtime errors (on my tests) like this

java.lang.NoSuchMethodError: 'java.util.List java.util.List.reversed()'

This occurs because of an "offending" line at the end of this little function:

fun MutableList<Byte>.increaseDataLengthBy(numberToIncrease: Int): MutableList<Byte> {
    val dataToIncrease = this
    //The increase method adds zeros to the right so we need to reverse the data so the zeros will
    //be in the left, therefore, if the original data length is larger than 1 we need to reverse it first,
    //so the final reverse will return it to its original order.
    if (dataToIncrease.size > 1) {
        dataToIncrease.reverse()
    }

    for (i in 0 until numberToIncrease) dataToIncrease.add(0)

    return dataToIncrease.reversed().toMutableList() // <-- THIS HAS THE ERROR
}

Now in the IDE I can hover over the word "reversed" and it shows mwe a little window talking about Kotlin.collections and how this function "Returns a list with elements in reverse order" and the code seems to exist so why do I get this runtime error?

(You might ask, "why are you messing around with all this 'reverse' nonsense, just use addFirst()" and that's a good point, but it seems to only work from sdk 35 upwards and I need to be backwards compatible to at least 26)


Solution

  • Many thanks to @MikeM. for suggestions (if you want to post an answer I will accept it)

    I changed the code to say explicitly

    java.util.Collections.reverse(dataToIncrease)
    return dataToIncrease.toMutableList()
    

    ...and that compiles and runs fine under sdk 35!

    The IDE suggested changing the static call with the kotlin stdlib so now I have

    dataToIncrease.reverse()
    return dataToIncrease.toMutableList()
    

    I looked up what the difference between "reverse and "reversed" is and it seems reversed always returns a read-only result....since I don't ever write to the results I get from this function - I instead copy them, it seems that this code will work well for me.

    Thanks for your help!