Search code examples
kotlinlanguage-design

What are the advantages of returning -1 instead of null in indexOf(...)?


When calling List.indexOf(...), what are the advantages of returning -1 rather than null if the value isn't present?

For example:

val list = listOf("a", "b", "c")
val index = list.indexOf("d")

print(index) // Prints -1

Wouldn't it be a cleaner result if index was null instead? If it had an optional return type, then it would be compatible with the elvis operator :? as well as doing things such as index?.let { ... }.

What are the advantages of returning -1 instead of null when there are no matches?


Solution

  • Just speculations but i could think of two reasons:

    The first reason is to be compatible with Java and its List.indexOf

    As the documentation states:

    Returns: the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element

    The second reason is to have the same datatype as kotlins binarySearch.

    Return the index of the element, if it is contained in the list within the specified range; otherwise, the inverted insertion point (-insertion point - 1). The insertion point is defined as the index at which the element should be inserted, so that the list (or the specified subrange of list) still remains sorted.

    Where the negative values actually hold additional information where to insert the element if absent. But since the normal indexOf method works on unsorted collections you can not infer the insertion position.