在 indexOf(...) 中返回 -1 而不是 null 有什么好处?
What are the advantages of returning -1 instead of null in indexOf(...)?
调用 List.indexOf(...)
时,如果值不存在,returning -1
比 null
有什么优势?
例如:
val list = listOf("a", "b", "c")
val index = list.indexOf("d")
print(index) // Prints -1
如果索引为 null
,结果不是更清晰吗?如果它有一个可选的 return 类型,那么它将与 elvis 运算符 :?
兼容,并且可以做诸如 index?.let { ... }
.
之类的事情
当没有匹配项时,returning -1
而不是 null
的优点是什么?
只是猜测,但我能想到两个原因:
第一个原因是为了兼容Java及其List.indexOf
如文档所述:
Returns:
the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element
第二个原因是具有与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.
负值实际上包含附加信息,如果不存在则在何处插入元素。但是由于正常的 indexOf
方法适用于未排序的集合,您无法推断插入位置。
要添加到@Burdui 的明确 ,这种行为的另一个原因是 -1
return 值可以用相同的原始 Int
类型表示作为 indexOf
函数的其他可能结果。
如果 indexOf
returned null
,则需要使其 return 类型可为空,Int?
,这将导致原语 return 值被装箱到一个对象中。 indexOf
通常在紧密循环中使用,例如,当搜索字符串中所有出现的子字符串时,在该热路径上进行装箱可能会使使用 indexOf
的成本高得令人望而却步。
另一方面,肯定存在性能无关紧要的情况,从 indexOf
中 returning null
会使代码更具表现力。有一个请求 KT-8133 为这种情况引入 indexOfOrNull
扩展。
同时,在 indexOf
的结果上调用 .takeIf { it >= 0 }
的解决方法允许实现相同的目的。
调用 List.indexOf(...)
时,如果值不存在,returning -1
比 null
有什么优势?
例如:
val list = listOf("a", "b", "c")
val index = list.indexOf("d")
print(index) // Prints -1
如果索引为 null
,结果不是更清晰吗?如果它有一个可选的 return 类型,那么它将与 elvis 运算符 :?
兼容,并且可以做诸如 index?.let { ... }
.
当没有匹配项时,returning -1
而不是 null
的优点是什么?
只是猜测,但我能想到两个原因:
第一个原因是为了兼容Java及其List.indexOf
如文档所述:
Returns: the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element
第二个原因是具有与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.
负值实际上包含附加信息,如果不存在则在何处插入元素。但是由于正常的 indexOf
方法适用于未排序的集合,您无法推断插入位置。
要添加到@Burdui 的明确 -1
return 值可以用相同的原始 Int
类型表示作为 indexOf
函数的其他可能结果。
如果 indexOf
returned null
,则需要使其 return 类型可为空,Int?
,这将导致原语 return 值被装箱到一个对象中。 indexOf
通常在紧密循环中使用,例如,当搜索字符串中所有出现的子字符串时,在该热路径上进行装箱可能会使使用 indexOf
的成本高得令人望而却步。
另一方面,肯定存在性能无关紧要的情况,从 indexOf
中 returning null
会使代码更具表现力。有一个请求 KT-8133 为这种情况引入 indexOfOrNull
扩展。
同时,在 indexOf
的结果上调用 .takeIf { it >= 0 }
的解决方法允许实现相同的目的。