After incrementing compileSdkVersion to 31 (Android 12), and when lint check is performed, the following issue appears:
Error: Call requires API level S (current min is 23): android.util.SparseArray#set [NewApi]
Has someone had a similar issue after incrementing this, and why does it occur?
set
was added in Android 12 and is just a copy of the put
function, which you can freely use instead.
The reason they copied the function with a different name is so array access syntax can work in Kotlin. When the Kotlin compiler sees a function in a Java class with the name set
and two parameters, it allows it to be called using array syntax like this:
mySparseArray.put(3, someObject)
// is the same as
mySparseArray[3] = someObject
But since they only added it in Android 12, it is not practical to use the new function if you are targeting anything less than Android 12 (sdk version 31), so it will take a few years to become useful.
In my opinion, it was a mistake to add this function to the base class, because now it is impossible to use array access syntax for a few years until it finally becomes sensible to make SDK 31 the minSdkVersion
. Before they added it, it was possible to use an extension function to have this functionality, but now an extension function cannot be used because its name would shadow the one in the base class. Also, lint doesn't show an error for the array access syntax, so it will crash at runtime if you use it. They should have put this in as an extension function in androidx-core-ktx
.
Edit: Looks like maybe this is fixed in an upcoming version, if I'm understanding "backport" correctly.