Hi... I'm getting index out of bounds exception fr...
# announcements
t
Hi... I'm getting index out of bounds exception from this code. anyone know why?
Copy code
private var worldSize: Int = 0
private var biomes: MutableMap<Biome, IntRange> = mutableMapOf()

data class PointData(val currentPoint: Int?, val currentBiome: Biome)

fun getPointData(point: Int): PointData {
    biomes.values.forEach {
        if (it.contains(point)) {
            return PointData(point, biomes.keys.elementAt(biomes.keys.indexOf(it)))
        }
    }
    return PointData(null, Savannah())
}
Exception in thread "main" java.lang.IndexOutOfBoundsException: Collection doesn't contain element at index -1.
This is the dictionary: The result should be Savannah as you would see below:
e
why do you keep doing this unnecessary
indexOf
t
@ephemient what do I do instead?
e
it
is a
IntRange
, of course
biomes.keys: Set<Biome>
is not going to contain it
iterate over the map's entries
t
@ephemient I actually swapped the keys and the values and it fixed it
@ephemient you can see the final code in code review.. I had some other mistakes also
e
Copy code
for ((biome, range) in biomes) {
    if (point in range) {
        return PointData(point, biome)
    }
}
K 2
👍 2
t
@ephemient ok thanks for this..
n
or
return biomes.entries.find { point in it.value } ?.let { PointData(point, it.key) } ?: PointData(null, Savannah())