Scala List indexOf 有错误?

Scala List indexOf has bug?

我正在阅读 scala API 的 List,我发现:indexOf(elem: A, from: Int)

所以我运行下面的代码:

scala> List(1,3,5,8).indexOf(8,-2)
res393: Int = 1

scala> List(1,3,5,8).indexOf(8,-3)
res391: Int = 0

为什么会这样? 我的 Scala 版本是 2.12.1(Java HotSpot(TM) 64 位服务器 VM,Java 1.8.0)。

此行为不是错误,只是未定义(虽然非常令人惊讶,并且根据您使用的集合不一致)。


List 上,.indexOf 将最终调用 .indexWhere(在 LinearSeqOptimized 上),其中负数将最终移动结果:

override /*SeqLike*/
def indexWhere(p: A => Boolean, from: Int): Int = {
  var i = from                 // -3
  var these = this drop from   // no effect
  while (these.nonEmpty) {
    if (p(these.head))
      return i                 // may return a negative number

    i += 1
    these = these.tail
  }
  -1
}

正如@adamwy 在评论中指出的那样,在 Vector 上使用负数调用 .indexOf 不会有相同的结果;它将调用 .indexWhere(在 IndexedSeqOptimized 上):

override /*SeqLike*/
def indexWhere(p: A => Boolean, from: Int): Int = {
  val start = from max 0        // completely ignores negatives 'from' input
  negLength(start + segmentLength(!p(_), start))
}

一个错误(尽管确实没有明确的文档说明当 from 为负时的预期结果)- 感谢您的问题,将在2.12.2修复:https://github.com/scala/scala/pull/5621

那么 - 好收获!