Right now the following code:
val q = listOf("potato", "tomato")[3]
will throw an exception (index out of bounds).
The fix for this, in Kotlin, is this:
val q = listOf("potato", "tomato").getOrNull(3)
What’s the reasoning behind this verbosity? There are other languages (Elm for example) that default to the optional behavior for index retrievals.
I think it’s best to move away from exceptions where possible. (compile-time safety > runtime errors)
I feel like the first code snippet should return a String?
and then if you want an exception to be thrown in the case of a failure, you’d have to explicitly call to that:
val q = listOf("potato", "tomato").getOrException(3)
I think applying this null > exceptions universally will result in fewer runtime failures.
In a similar vein, I think it’d be cool to be able to run Kotlin with a config option that turns all Any!
types to Any?
, so when utilizing Java libraries we don’t have to worry about NPEs. I understand the reasoning behind this (to get people to move to Kotlin from Java without having to implement safety that they didn’t have before), but I think that decision should only be temporary.