Issue
I have a list of images and a variable with can be anything from -1 to 13.
But the list contains only 3 indexes, so I have set a condition.
items[if(myInt == null) R.drawable.placholder else myInt
But it crashes my app with this error,
java.lang.ArrayIndexOutOfBoundsException: length=4; index=4
My Code
val items = listOf(R.drawable.red, R.drawable.green, R.drawable.blue)
Image(painter = painterResource(items[if(myInt==null) R.drawable.placholder else myInt]), contentDescription = null)
Solution
The shortest solution is using kotlin getOrElse. You can specify -1
instead of null
:
items.getOrElse(myInt ?: -1) { failedIndex -> R.drawable.ic_undo }
A more detailed solution is to check if item.indices
contains your index:
if (myInt != null && items.indices.contains(myInt)) {
items[myInt]
} else {
R.drawable.ic_undo
}
Answered By - Philip Dukhov