I have one question. I recently read [“Null is you...
# announcements
l
I have one question. I recently read [“Null is your friend, not a mistake”](https://medium.com/@elizarov/null-is-your-friend-not-a-mistake-b63ff1751dd5) by Roman Elizarov. So I found out that I shouldn’t avoid null, I should use it properly. And that is philosophy of Kotlin. If so, Why is there no
indexOfOrNull
function in Kotlin? According to Roman Elizarov, Null is the cleanest and most obvious way to indicate that there is no value. But There is only
indexOf
function that return -1 in kotlin.
m
probably an oversight. Of all the list functions, I use indexOf almost never. You can make a youtrack issue for them if you want this (I probably want it to). For now, you can write an extension function for it:
Copy code
fun <T> Iterable<T>.indexOfOrNull(element: T) = indexOf(element).takeIf{ it >= 0}
d
indexOf returns an Int, which is not a nullable type.
l
@Michael de Kaste Thank you 👍
l
indexOf returns -1 if not found, that's kinda a convention for not found indexes
m
@louiscad indexOf returning a negative integer has been a convention I'd argue mostly because in java, primitives can't be null and therefor they needed another way to conveniently tell the caller that there is no such element in the list. It's fine that it exists as is, but most other functions have a "orNull" appendage to better translate to the mindset of Kotlin. for instance, arrays (and lists) have always thrown an "indexOutOfBoundsException" if you would try and get a value outside its ranges. Kotlin has provided a "getOrNull" function to accomodate the need for a "There is no value on this index" function. I agree with @Luis Daivid that, with that mindset, there should also be a "indexOfOrNull" function if only purely for the convenience of handling it in the same way as one would handle all the other functions.
l
In the meantime, you can write
takeIf { it >= 0 }
or
takeIf { it != -1 }
if you need to have null instead of -1.
z
The standard library is continuously getting new features. You could file an issue to add this function, the tracker link is in the channel description.