with the introduction of a lot of `orNull` functio...
# stdlib
m
with the introduction of a lot of
orNull
functions in mind, I was unpleasantly surprised there is no such thing as
List<T>.indexOfFirstOrNull
s
Looks like it’s in YouTrack but was closed on the basis that
null
isn’t really much more useful than
-1
. Personally, I’m with you; I would much prefer
null
. An unexpected
-1
can easily go unnoticed, leading to errors down the line. Whereas the type system forces you to handle
null
, so if there’s a chance my index won’t exist, I definitely want that. I suppose the downside of using
null
is that the return type would have to be boxed. But since we’re only dealing with a single value here, I don’t see that being a big concern.
m
how is 'null' not more usefull than''-1' 😛?
but yeah I agree, it actually almost went past code review until someone notified me that I didn't catch the 'defaultValue'
its definitely not typesafe to use just
indexOfFirst
💯 2
d
If the issue was just boxing, I'd instead like to see a value class wrapping around
Int
where you'd either clearly assert that you're getting a useful integer or have to write a case for when the item is not found, maybe
value class Index(private val i: Int)
.
m
you can write it as
list.indexOfFirst(foo).takeUnless { it == -1 }