from <https://kotlinlang.org/api/latest/jvm/stdlib...
# getting-started
y
from https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-array/get.html "If the index is out of bounds of this array, throws an
IndexOutOfBoundsException
except in Kotlin/JS where the behavior is unspecified." does this mean I can't rely on catching an
IndexOutOfBoundsException
here? (this is just curiosity, not trying to solve a specific issue)
s
That's how I'd interpret that line in the docs, for sure
If there's any doubt about whether the index is in range, I'd always go for
getOrElse
or
getOrNull
instead of
get
I think it comes down to the fact that in JavaScript itself, indexing into an array just returns
undefined
if it's out of bounds
y
Turns out that's because JS doesn't throw in an OOB case, it instead gives you
undefined
(because JS). Edit: Sam beat me to the punch lol!
🫰 1
thank you color 1
y
thanks for the answers. so JavaScript does JavaScript things, but why would calling this from Kotlin have unspecified behavior?
or does "Kotlin/JS" not mean what I think it means
(re:
getOrNull
- doesn't work in the case where you're indexing into a
List<T?>
, and so
getOrNull
returning null is ambiguous. which of course you can solve in other ways)
s
Well, having Kotlin/JS arrays behave the same as the JS arrays they're calling through to is probably the path of least resistance. "Unspecified" is kind of a cop-out; I would guess it basically means "it works one way right now, but we don't really like it so we might change it in the future"
thank you color 1
y
a quick search told me that "Kotlin/JS" does indeed not mean what I think it means. now that I read about it, this all makes sense. well, TIL.
j
My personal approach to this was to check if the index is contained within the
indices
range:
Copy code
if (index in myArray.indices) {
    println(myArray[index])
}
Before, I was trying to catch the errors, but it wasn't working for all targets
y
yeah, checking the index works. and in the general case you could define some sort of tri-state sealed class and write a
getOrNull
equivalent that returns one of:
class Exists(val T)
,
object ExistsButNull
,
object OutOfRange
. or use some general
Either<A, B>
class and write a
getOrNull
equivalent that returns
Either<T?, Unit>
or something like that. etc.